|
发表于 2011-11-13 20:13:35
|
显示全部楼层
- # include <stdio.h>
- struct student
- {
- char accounts[20];
- char password[20];
- }person[3];
- void print (void);
- void main()
- {
- FILE *fp;
- int i = 0;
- if (! (fp = (fopen ("1", "wb")))) //判断文件是否打开成功;
- {
- printf("文件打开失败!!\n");
- return ;
- }
-
- while (1)
- {
- printf("请输入帐号:");
- scanf("%s", &person[i].accounts);
- rewind(stdin); //清空缓冲区!!
- printf("请输入密码:");
- scanf("%s", &person[i].password);
- rewind(stdin); //同上!!
- printf("保存按下任意键,取消按n!");
-
- if (getchar() == 'n')
- {
- printf("\n");
- printf("取消成功!!\n");
- }
- else
- {
- printf("\n");
- printf("保存成功!!\n");
- //fseek(fp, sizeof(struct student), 0); //如果这句加了,每次都把
- //文本指针指向了第一个,
- //则第二次输入的数据会覆盖第一次!!
- fwrite(&person[i], sizeof(struct student), 1, fp);
- i++;
- }
- if (i >= 3)
- {
- printf("文件已满无法存储!!\n");
- break;
- }
- }
- fclose (fp);
- print();
- }
- void print (void) //读取刚刚写入的文件,打印到屏幕!!
- {
- FILE *fp;
- int i;
- if(!(fp = fopen("1", "rb")))
- {
- printf("cannot open a file!");
- return ;
- }
- for(i = 0; i < 3; i++)
- {
- fread(&person[i], sizeof(struct student), 1, fp); //读去文件内容到person结构体数组;
- printf("帐号:%s\n密码:%s\n", person[i].accounts, person[i].password); //打印!!
- }
- }
复制代码 我也是才学文件的!!有问题一起发掘啊!!!{:1_1:} |
|