C语言使用fread()函数无法读取文件内容问题求助
问题根因
代码存在几处逻辑错误,最核心的是文件读写位置指针的问题:
- 调用
fprintf往文件写入内容后,FILE结构体内部维护的读写位置指针会停在刚写入内容的末尾,此时直接调用fread会从文件末尾位置开始读,自然读不到任何有效内容。写入完成后必须先把位置指针重置到文件开头,才能读取到刚写入的内容。 - 其余会导致运行异常的问题:
fread的第三个参数是要读取的元素个数,原代码写的是1,意味着最多只读1个字节,不可能读完整行输入fread不会自动在读取到的内容末尾补C语言字符串必需的\0终止符,直接用printf按字符串打印会出现乱码甚至内存访问错误- 全程没有校验
fopen、malloc、fgets的返回值,一旦文件打开失败、内存申请失败或者输入读取失败,程序会触发未定义行为 - 打开的文件流、
malloc申请的堆内存没有在程序退出前释放/关闭,会造成资源泄漏
修正后代码
#include <stdio.h> #include <stdlib.h> int main(void) { FILE *file1 = fopen(".out", "w+"); if (file1 == NULL) { printf("Failed to open file\n"); return 1; } char *s = malloc(513); if (s == NULL) { printf("Failed to allocate memory\n"); fclose(file1); return 1; } if (fgets(s, 513, stdin) == NULL) { printf("Failed to read user input\n"); free(s); fclose(file1); return 1; } if (fprintf(file1, "%s", s) < 0) { printf("Something failed while writing to the file\n"); free(s); fclose(file1); return 1; } else { // 把文件读写位置重置到开头 rewind(file1); char *t = malloc(513); if (t == NULL) { printf("Failed to allocate memory\n"); free(s); fclose(file1); return 1; } // 最多读取512个字节,预留1位存字符串终止符 size_t read_bytes = fread(t, sizeof(char), 512, file1); t[read_bytes] = '\0'; printf("Success! Input was: %s \n", t); free(t); } free(s); fclose(file1); return 0; }
补充说明
重置文件指针可以用rewind(file1),也可以用fseek(file1, 0, SEEK_SET),二者效果一致,都是将读写位置偏移到文件起始处。同一个读写流写完后立刻读的场景下,调用位置重置函数会自动刷新IO缓冲区,不需要额外手动调用fflush。
内容的提问来源于stack exchange,提问作者Mario Olcina
相关产品推荐
相关产品推荐

