【问题标题】:Why does fread() not work for files with html content?为什么 fread() 不适用于具有 html 内容的文件?
【发布时间】:2018-01-31 14:17:17
【问题描述】:

我尝试使用以下代码读取一些文件:

主要:

#define RESPONSE_MAX_LENGTH (1024 * 1024)       // Should be 1MB
char file_content[RESPONSE_MAX_LEGNTH];
memset(&file_content, 0, RESPONSE_MAX_LEGNTH);

request_get_file("/User/...", file_content);

函数声明:

int request_get_file(char* requested_file_path, char* buf) {
    int file_size = 0;
    FILE* fp = NULL;

    if ((fp = fopen(requested_file_path, "r+")) == NULL) {
        return errno;
    }

    fseek(fp, 0L, SEEK_END);
    file_size = (int)ftell(fp);
    rewind(fp);
    errno = 0;
    if (fread(buf, 1, file_size, fp) == 0) {
        if (!feof(fp)) {
            if (ferror(fp)) {
                printf("An error occured while reading the requested file. File size: %d\n", file_size);
                perror("fread()");
                return errno;
            }
        }
    }
    fclose(fp);
}

我可以读取 .txt 文件,但是当我打开一个 html 文件时,我收到一条错误消息:

fread(): Bad address(使用 perror("fread") 创建) errno = 14

由于某种原因,此错误仅发生在某些特定文档中。

解决方案:

我刚刚意识到问题似乎与特定文件有关。将我的 test.html 重命名为 test.txt 并尝试打开此文件后,错误仍然存​​在。这可能与文件内容有关吗? => 是的,因为我写入数据的缓冲区太小了。

我该如何解决这个问题?

【问题讨论】:

  • 您确定文件名是.html 而不是.htm?
  • 请显示程序的逐字输出并显示minimal reproducible example。特别显示buf是什么以及它是如何分配的,问题很可能是那里
  • ^^^ @MichaelWalz 所说的。 'buf' 在哪里声明,它有多大?我不认为您的“test.html”文件比您正在测试的文本文件大得多?
  • @T.Meyer 不,它不应该被删除,但你需要显示request_get_file 是如何被调用的,因为问题出在那里。但是程序的设计无论如何都是错误的,应该由request_get_file 分配足够大小的缓冲区,因为它只是那里知道文件大小的地方。如果你有一个非常大的文件,你的新程序会再次失败。
  • 不要在标题中标记您的问题“[已解决]”。 Mark them solved by accepting an answer。由于此处没有没有答案发布(但您已在问题帖子中添加了解决方案),如果您愿意,您可以自行回答并接受您自己的答案。

标签: html c


【解决方案1】:

问题是我写入的缓冲区太小,无法容纳fread() 读取的所有数据。

我更新的代码:

主要:

char* buf = NULL;
request_get_file("/User/...", &buf);

函数声明:

int request_get_file(char* requested_file_path, char** buf) {
    int file_size = 0;
    FILE* fp = NULL;

    if ((fp = fopen(requested_file_path, "r+")) == NULL) {
        return errno;
    }

    fseek(fp, 0L, SEEK_END);
    file_size = (int)ftell(fp);
    rewind(fp);
    errno = 0;

    if ((*buf = calloc(file_size + 1, sizeof(char))) == NULL) {
        perror("calloc()");
        return errno;
    }

    if (fread(*buf, 1, file_size, fp) == 0) {
        if (!feof(fp)) {
            if (ferror(fp)) {
                printf("An error occured while reading the requested file. File size: %d\n", file_size);
                perror("fread()");
                return errno;
            }
        }
    }
    fclose(fp);
}

【讨论】:

  • @MichaelWalz 为什么会这样?你能改进我的答案吗?由于 calloc(),buf 没有值吗?
  • 抱歉,我在你的代码中遗漏了一些东西,它看起来对我来说是正确的。忘记错误的cmets。我已经删除了它们。
猜你喜欢
  • 2019-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-20
  • 2014-01-10
相关资源
最近更新 更多