qq_34680450
qq_34680450
2017-12-14 13:47

文件 rb+ 模式的读写问题

5
  • c

typedef struct NEW_MAN
{
int num;
char name[10];
}MAN;

void write_content()
{
FILE* pfile1 = fopen("c:\test_space\test_struct_w+.dat", "wb");
MAN data[3] = { { 1, "s" }, { 2, "z" }, { 3, "r" } };
fwrite(data, sizeof(MAN), 3, pfile1);
fclose(pfile1);
}

int main(int argc, char* argv[])
{
write_content();
struct stat mystat1 = { 0 };
stat("c:\test_space\test_struct_w+.dat", &mystat1);
int len = (mystat1.st_size)/(sizeof(MAN));

FILE* pfile2 = fopen("c:\\test_space\\test_struct_w+.dat", "rb+");
//fseek 测试
fseek(pfile2, sizeof(MAN), SEEK_SET);
int pos1 = ftell(pfile2);//16

//
MAN data_tmp = { 0 };
fread(&data_tmp,sizeof(MAN),1,pfile2);
printf("%d,%s\n", data_tmp.num, data_tmp.name);
//1.为什么加了fread(上面的三行代码),下面的fwrite就不起作用了,也就是写入不了




MAN myman2 = { 4, "zz" };
fwrite(&myman2, sizeof(MAN), 1, pfile2);
int pos2 = ftell(pfile2);//32

fseek(pfile2, 0, SEEK_SET);
MAN data2[3] = { 0 };
fread(data2, sizeof(data2), 3, pfile2);
int pos3 = ftell(pfile2);//48

for (int i = 0; i < len; i++)
{
    printf("%d,%s\n", data2[i].num, data2[i].name);
}
fclose(pfile2);


system("pause");
return 0;

}

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

4条回答

为你推荐