c - 读取文件失败

标签 c file fread

我正在从文件中读取字符串。在第二次或第三次执行该函数后,一个或多个随机字符会附加到缓冲区字符串中,我不知道为什么会发生这种情况。

这是一段代码:

scorefile = fopen("highscore.dat", "rb");

if (scorefile)
{
    fseek(scorefile, 0, SEEK_END);
    length = ftell(scorefile);
    fseek(scorefile, 0, SEEK_SET);
    buffer = malloc(length);
    if (buffer)
    {
        fread(buffer, 1, length, scorefile);
    }
    fclose(scorefile);
}

我在这里做错了什么吗?

最佳答案

让我们把一切都说清楚并变得更加健壮:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

char *loadScoreFile(const char *filename)
{
    char *buffer = NULL;

    FILE *scorefile = fopen(filename, "r");

    if (scorefile != NULL)
    {
        (void) fseek(scorefile, 0, SEEK_END);
        int length = ftell(scorefile);

        (void) fseek(scorefile, 0, SEEK_SET);

        buffer = malloc(length + 1);

        if (buffer != NULL)
        {
            assert(length == fread(buffer, 1, length, scorefile));

            buffer[length] = '\0';
        }
        (void) fclose(scorefile);
    }

    return buffer;
}

int main()
{
    for (int i = 0; i < 10; i++)
    {
        char *pointer = loadScoreFile("highscore.dat");

        if (pointer != NULL)
        {
            printf("%s", pointer);
            free(pointer);
        }
    }

    return 0;
}

关于c - 读取文件失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39317661/

相关文章:

c - 在不同级别的函数中传递参数

c - 函数返回链表中最旧的值

c - FUSE:传输端点未连接

c - 将文件文本放入 C 中的变量中

c - 如何从 CSV 文件(C 语言)读取和写入寄存器?

c - C 中的套接字编程错误

file - 如何提交非英文文件?

c++ - 如何在以前读取的行中找到一些单词并在输出中删除它 - c++中的读/写字符串

c - 以十六进制打印 : program adds additional 0xFFs

c - 这个程序中的 fread 有什么问题?