|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 GSMNC 于 2017-4-24 21:56 编辑
各位大神求指教,为什么我的代码编译通过,但测试出错
- #include <stdio.h>
- #include <stdlib.h>
- #define total 5
- int main()
- {
- int i;
- char ch;
- char filename[10];
- FILE *fp;
- struct student
- {
- char name[10];
- char sex;
- int num;
- int score;
- }a[total];
- printf("Please input student's information,including name,sex,num,score.\n");
- for(i = 0; i < total; i++)
- {
- scanf("%s %c %d %d", a[i].name, &a[i].sex, &a[i].num, &a[i].score);
- }
- printf("Enter file's name.\n");
- scanf("%s", filename);
- if ((fp = fopen(filename, "r+")) == NULL)
- {
- printf("Open operation failed.\n");
- exit(0);
- }
- ch = getchar();
- for (i = 0; i < total; i++)
- {
- if ((fwrite(&a[i], sizeof(struct student), 1, fp)) != 1)
- {
- printf("write file fails\n");
- }
- }
- fclose(fp);
- printf("Hello world!\n");
- return 0;
- }
复制代码
fwrite这个函数以二进制形式对文件进行操作。它写入文件是二进制写入的,所以是乱码。
可以使用fprintf函数写入文件。
- #include <stdio.h>
- #include <stdlib.h>
- #define total 5
- int main()
- {
- int i;
- char c='\n';
- char ch;
- char filename[10];
- FILE *fp;
- struct student
- {
- char name[10];
- char sex;
- int num;
- int score;
- }a[total];
- printf("Please input student's information,including name,sex,num,score.\n");
- for(i = 0; i < total; i++)
- {
- scanf("%s %c %d %d", a[i].name, &a[i].sex, &a[i].num, &a[i].score);
- }
- printf("Enter file's name.\n");
- scanf("%s", filename);
- if ((fp = fopen(filename, "r+")) == NULL)
- {
- printf("Open operation failed.\n");
- exit(0);
- }
- ch = getchar();
- for (i = 0; i < total; i++)
- {
- /* if ((fwrite(a, sizeof(struct student), 3, fp)) != 1)
- {
- printf("write file fails\n");
- }*/
- if(fprintf(fp,"%s %c %d %d %c", a[i].name,a[i].sex,a[i].num,a[i].score,c)<0)
- {
- printf("write file fails\n");
- }
- }
- fclose(fp);
- //printf("Hello world!\n");
- return 0;
- }
复制代码
|
|