如何从文件加载c字符串

问题描述 投票:0回答:1

我的代码不断从内部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字符串逐行加载。有人可以帮忙吗?

c c-strings cfile
1个回答
0
投票

您想要这个:

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);
}

您仍然需要确保没有缓冲区溢出。


您的错误代码:

    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
    }
© www.soinside.com 2019 - 2024. All rights reserved.