gpt4 book ai didi

c - 读取二进制文件的全部内容

转载 作者:太空狗 更新时间:2023-10-29 16:09:13 24 4
gpt4 key购买 nike


我有这段 C 代码:

[...]
struct stat info;
char *filename = "just_a_binary_file";
stat(filename, &info);
printf("FILE SIZE: %d\n", info.st_size);

char *content = (char *)malloc(info.st_size * sizeof(char *));
FILE *fp = fopen(filename, "rb");
fread(content, info.st_size, 1, fp);
fclose(fp);

printf("STRING LENGTH: %d\n", strlen(content));
[...]

输出是:

FILE SIZE: 20481
STRING LENGTH: 6

问题是文件包含一些零字节,当我将文件内容放入变量 char* 时,字符串在第一次出现“\0”时被截断(恰好是 chr(0))。

问题是如何将完整的二进制内容放入变量 char* 中?

最佳答案

这是您的代码的修改版本。将其与您的进行比较。

struct stat info;
const char *filename = "just_a_binary_file";
if (stat(filename, &info) != 0) {
/* error handling */
}
printf("FILE SIZE: %lu\n", (unsigned long)info.st_size);

char *content = malloc(info.st_size);
if (content == NULL) {
/* error handling */
}
FILE *fp = fopen(filename, "rb");
if (fp == NULL) {
/* error handling */
}
/* Try to read a single block of info.st_size bytes */
size_t blocks_read = fread(content, info.st_size, 1, fp);
if (blocks_read != 1) {
/* error handling */
}
fclose(fp);

/*
* If nothing went wrong, content now contains the
* data read from the file.
*/

printf("DATA LENGTH: %lu\n", (unsigned long)info.st_size);

请注意,这种方法在某些情况下仍然容易出错。例如,stat() 会提供您调用 stat() 时文件的大小。文件大小可能在调用 stat() 和实际读取文件之间发生变化。

关于c - 读取二进制文件的全部内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7013307/

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