简体   繁体   English

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

[英]how to load a c string from a file

my code keeps throwing a segmentation fault from internal c libraries, my code is the following:我的代码不断从内部 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);
            }

it is meant to load all the data from a file as a c string, line by line.它旨在将文件中的所有数据作为 c 字符串逐行加载。 can anyone help?谁能帮忙?

You want this:你要这个:

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

You still need to make your that there is no buffer overflow.您仍然需要确保没有缓冲区溢出。 Possibly you need touse realloc in order to expand the buffer if the initial length of the buffer is too small.如果缓冲区的初始长度太小,您可能需要使用realloc来扩展缓冲区。 I leave this as an exercise to you.我把这个作为练习留给你。


Your wrong code:你的错误代码:

    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
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM