我在下面编写了一个函数来将文件的内容读取到内存中。 它在我的本地计算机(Ubuntu 32位)上运行良好,但在服务器(CentOS 64位)上产生错误的结果。
错误情况: 对于 40 字节的文件,内容如下,在 64 位操作系统上,它给出了错误的结果。
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
代码:
char* file_get_contents(const char *filename) {
FILE *stream = NULL;
char *content = NULL;
size_t ret;
struct stat st;
if ((stream = fopen(filename,"r")) == NULL) {
fprintf(stderr, "Failed to open file %s\n", filename);
exit(1002);
}
if(stat(filename, &st) < 0) {
fprintf(stderr, "Failed to stat file %s\n", filename);
exit(1002);
}
content = malloc(st.st_size);
ret = fread(content, 1, st.st_size, stream);
if (ret != st.st_size) {
fprintf(stderr, "Failed to read file %s\n", filename);
exit(1002);
}
fclose(stream);
return content;
}
最佳答案
调用者无法正确使用您的file_get_contents
。它返回一个 char * 但不返回它的长度,也不返回一个字符串(即它不是以 null 结尾的。)。
只要您正在阅读文本,就可以执行以下操作:
content = malloc(st.st_size + 1); // + 1 here for the nul terminator
ret = fread(content, 1, st.st_size, stream);
if (ret != st.st_size) {
fprintf(stderr, "Failed to read file %s\n", filename);
exit(1002);
}
content[st.st_size] = 0; //nul terminate
关于c - 读取文件内容到内存,32位操作系统和64位操作系统结果不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11984300/