gpt4 book ai didi

html - 为什么 fread() 不适用于包含 html 内容的文件?

转载 作者:行者123 更新时间:2023-11-30 16:36:17 26 4
gpt4 key购买 nike

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

主要:

#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():错误地址(使用 perror("fread") 创建)错误号 = 14

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

解决方案:

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

如何解决这个问题?

最佳答案

问题是我写入的缓冲区太小,无法容纳 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);
}

关于html - 为什么 fread() 不适用于包含 html 内容的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48544319/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com