如何从文件中加载 C 字符串

how to load a c string from a file

我的代码不断从内部 c 库中抛出分段错误,我的代码如下:

        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
    }