在文件读取中添加null的位置

时间:2018-02-09 09:17:22

标签: c file

在将文件读入char *时,应该在哪里添加null以及为什么? Option1或option2,似乎都在编译。

char* load_file(char const* path)
{
    char* buffer = 0;
    long length;
    FILE * f = fopen (path, "rb"); 

    if (f)
    {
        fseek (f, 0, SEEK_END);
        length = ftell (f);
        fseek (f, 0, SEEK_SET);
        buffer = (char*)malloc ((length+1)*sizeof(char));
        if (buffer)
        {
            fread (buffer, sizeof(char), length, f);
        }
        fclose (f);
    }
    buffer[length] = '\0'; //option1
    buffer[length+1] = '\0'; //Option2
    return buffer;
}

1 个答案:

答案 0 :(得分:4)

通过malloc来电,您可以分配length + 1个字符的“数组”,索引从0length(含)。因此,正确的选项只能是“option1”。