如何从文件中加载c字符串
我的代码不断从内部c库抛出分段错误,我的代码如下:如何从文件中加载c字符串,c,c-strings,cfile,C,C Strings,Cfile,我的代码不断从内部c库抛出分段错误,我的代码如下: char *vertexShaderCode = (char *)calloc(1024, sizeof(char)); FILE *shaderFile; shaderFile = fopen("./shaders/vertex.glsl", "r"); if(shaderFile) { //TODO: load file
char *vertexShaderCode = (char *)calloc(1024, sizeof(char));
FILE *shaderFile;
shaderFile = fopen("./shaders/vertex.glsl", "r");
if(shaderFile)
{
//TODO: load file
for (char *line; !feof(shaderFile);)
{
fgets(line, 1024, shaderFile);
strcat(vertexShaderCode, line);
}
它意味着以c字符串的形式逐行加载文件中的所有数据。有人能帮忙吗?你想要这个:
char *vertexShaderCode = (char *)calloc(1024, sizeof(char));
FILE *shaderFile;
shaderFile = fopen("./shaders/vertex.glsl", "r");
if (shaderFile == NULL)
{
printf("Could not open file, bye.");
exit(1);
}
char line[1024];
while (fgets(line, sizeof(line), shaderFile) != NULL)
{
strcat(vertexShaderCode, line);
}
您仍然需要确保没有缓冲区溢出。如果缓冲区的初始长度太小,可能需要使用realloc来扩展缓冲区。我把这个作为练习留给你
您的错误代码:
char *vertexShaderCode = (char *)calloc(1024, sizeof(char));
FILE *shaderFile;
shaderFile = fopen("./shaders/vertex.glsl", "r"); // no check if fopen fails
for (char *line; !feof(shaderFile);) // wrong usage of feof
{ // line is not initialized
// that's the main problem
fgets(line, 1024, shaderFile);
strcat(vertexShaderCode, line); // no check if buffer overflows
}
,即使伪装,TODO:检查fopen是否失败。不断抛出错误:哪些错误?在您的问题中发布逐字记录错误消息。你可以回答你的问题。按照我在第二条评论中告诉你的去做。2.根据第一条注释删除错误的feof。3.请确保使用calloc分配足够的内存,如果文件太长,则会出现缓冲区溢出,这通常表现为分段错误。我同意@Jabberwocky的观点,您的文件很可能超过1024个字符,并且您没有在缓冲区上调用realloc我如何解释缓冲区溢出,我不知道怎么做。@ShadowLynch您的代码基本上是在vertexShaderCode缓冲区中积累信息,其大小为1024。如果你继续在缓冲区中添加信息,它就会溢出,就像你在装满水的杯子里继续倒水一样,水也会溢出。提示:使用铅笔和一张纸。提示2:如果缓冲区太小,请使用realloc函数扩展缓冲区。在while循环中,可以检查strlenline+strlenvertexShaderCode是否小于1024。如果不是,它可能是一个添加realloc或至少一个警告printf的好地方。