69,371
社区成员
发帖
与我相关
我的任务
分享
#include "stdafx.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
struct Roommate{
char name[6];
char NO[8];
char addr[10];
};
int _tmain(int argc, _TCHAR* argv[])
{
struct Roommate Rom[2] = {0};
FILE *file = NULL;
if(!(file = fopen("a.txt", "w"))) {
printf("Create File failed!\n");
exit(-1);
}
printf("Please input four times Roommate data: Name NO Addr\n");
for(int i=0; i<2; ++i) {
scanf("%s%s%s", Rom[0].name, Rom[0].NO, Rom[0].addr);
fwrite((const void *)&Rom[0], sizeof(struct Roommate), 1, file);
}
fclose(file);
/* Read from file*/
file = NULL;
if(!(file = fopen("a.txt", "r"))) {
printf("Create File failed!\n");
exit(-1);
}
printf("Read from the file: Name NO Addr\n");
fread((void *)Rom, sizeof(struct Roommate), 2, file);
for(int i=0; i<2; ++i) {
printf("i=%d Name:%s\tNO:%s\tAddr:%s\n", i, Rom[i].name, Rom[i].NO, Rom[i].addr);
}
fclose(file);
while(getchar()) ;
return 0;
}