简体   繁体   English

C 中函数读取文件的意外行为

[英]Unexpected behaviour from function reading file in C

Ok, I'll start of by saying that i'm making a webserver.好的,我首先要说我正在制作一个网络服务器。 And i have a function getFileContent i use to get my content from my files that looks like this我有一个函数getFileContent我用来从我的文件中获取我的内容,看起来像这样

char* getFileContent(char *filename)
{
    long length;
    char *buffer;
    FILE *f = fopen (filename, "r");
    if (f) {
        fseek (f, 0, SEEK_END);
        length = ftell (f);
        fseek (f, 0, SEEK_SET);
        buffer = malloc (length + 1);
        if (buffer) {
            fread (buffer, 1, length, f);
        }
        fclose (f);
    }

    if (buffer != 0) {
        return buffer;
    } else {
        return NULL;
    }
}

And when calling this function i get some weird behaviour.当调用这个函数时,我得到了一些奇怪的行为。
If i only call it once like this如果我像这样只调用一次
char *fileContent = getFileContent(path);
for example when i'm getting the filecontent to return, it appends a 2 or 3 weird characters.例如,当我要返回文件内容时,它会附加 2 或 3 个奇怪的字符。
But if i call it twice to the same variable, it appends another set of weird characters.但是如果我对同一个变量调用两次,它会附加另一组奇怪的字符。

However, if i call the function a third time, at the beginning of the program, in main .但是,如果我在程序开始时在main第三次调用该函数。 By for example getting the content in /etc/hosts/ to a completely different and unused variable, it prints the output normally later in the code.例如,通过将/etc/hosts/的内容获取到一个完全不同且未使用的变量,它会在代码的后面正常打印输出。

I've tried to see the problem but it seems so random and i'd really appreciate it if anyone could help me with it.我试图看到这个问题,但它似乎很随机,如果有人能帮助我,我真的很感激。

When you read the file content, your buffer is not NUL terminated.当您读取文件内容时,您的缓冲区不会以NUL终止。 So if you're treating it as a C-string (eg printf), you're invoking undefined behavior.因此,如果您将其视为 C 字符串(例如 printf),则您正在调用未定义的行为。

You should check the return value of fread and place a '\\0' after the last byte read.您应该检查fread的返回值并在读取的最后一个字节后放置一个'\\0'

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

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