测试代码(测试环境ubuntu + gcc):
#include <stdio.h>
#include <string.h>
struct que_st1 {
int a;
int b;
int c;
char buf[100];
}str1;
struct que_st2 {
int a;
int b;
int c;
char buf[1000];
}str2;
// 测试1,无存储文件时,直接读取,运行输出
//fopen: No such file or directory
//len=0
//str2=0 0 0, 0
//Segmentation fault (core dumped)
int main()
{
FILE *fp = NULL;
size_t len;
str1.a = 100;
str1.b = 200;
str1.c = 300;
str1.buf[99] = 99;
// fp = fopen("/home/wy/ctyq/ctyq_mini/save.ty", "w+");
// len = fwrite(&str1, sizeof(str1), 1, fp);
// printf("len=%d\n", len);
// fclose(fp);
fp = fopen("/home/wy/ctyq/ctyq_mini/save.ty", "r+");
if (fp == NULL)
{
perror("fopen");
}
printf("len=%d\n", len);
printf("str2=%d %d %d, %d\n", str2.a, str2.b, str2.c, str2.buf[99]);
len = fread(&str2, sizeof(str2), 1, fp);
printf("len=%d\n", len);
printf("str2=%d %d %d, %d\n", str2.a, str2.b, str2.c, str2.buf[99]);
fclose(fp);
system("rm -rf save.ty");
}
// 测试2,无存储文件时,直接读取,运行输出
//len=1
//len=0
//str2=100 200 300, 99
int main()
{
FILE *fp = NULL;
size_t len;
str1.a = 100;
str1.b = 200;
str1.c = 300;
str1.buf[99] = 99;
fp = fopen("/home/wy/ctyq/ctyq_mini/save.ty", "w+");
len = fwrite(&str1, sizeof(str1), 1, fp);
printf("len=%d\n", len);
fclose(fp);
fp = fopen("/home/wy/ctyq/ctyq_mini/save.ty", "r+");
if (fp == NULL)
{
perror("fopen");
}
len = fread(&str2, sizeof(str2), 1, fp);
printf("len=%d\n", len);
printf("str2=%d %d %d, %d\n", str2.a, str2.b, str2.c, str2.buf[99]);
fclose(fp);
system("rm -rf save.ty");
}
// 测试3,先写文件,再用另一种格式读取,运行输出
//lenw=112
//lenr=112
//str2=100 200 300, 99
int main()
{
FILE *fp = NULL;
size_t len;
str1.a = 100;
str1.b = 200;
str1.c = 300;
str1.buf[99] = 99;
fp = fopen("/home/wy/ctyq/ctyq_mini/save.ty", "w+");
len = fwrite(&str1, 1, sizeof(str1), fp);
printf("lenw=%d\n", len);
fclose(fp);
fp = fopen("/home/wy/ctyq/ctyq_mini/save.ty", "r+");
len = fread(&str2, 1, sizeof(str2), fp);
printf("lenr=%d\n", len);
printf("str2=%d %d %d, %d\n", str2.a, str2.b, str2.c, str2.buf[99]);
fclose(fp);
}
1、fopen操作的返回值一定要判断,以免因为无文件或不能创建文件导致 fwrite 或 fread操作发生段错误。
2、fread读取单元超过文件大小时,返回值为0,这种情况下要注意,实际上接收单元str2,已经被赋值,要小心使用以免因此异常。
3、补充说明2,注意下面这两种写法,文件实际体积小于读取体积时,写法2会返回0,但实际上str2已经赋值一部分。
fread(&str2, 1, sizeof(str2), fp);
fread(&str2, sizeof(str2), 1, fp);