首页 > 解决方案 > .txt 的内容看起来很乱,其内容是使用 C 编写的

问题描述

出于学习目的,我在名为“record.txt”的文件中编写了一个学生记录,并且我的代码中并没有真正看到任何问题(在我看来)。

这是我尝试过的代码:

# include<stdio.h>
# include<stdlib.h>

int main() {
    FILE *fp;
    char choice = 'y';

    struct student {
        char name[50];
        int rollno;
        float percentage;
    };
    struct student s;


fp = fopen("record.txt", "w");
if(fp == NULL) {
    puts("Unable to open the file");
    exit(0);
}

while(choice == 'y') {

printf("Enter name, rollno and percentage of student: ");
scanf("%s %d %f", &s.name, &s.rollno, &s.percentage);

fwrite(&s, sizeof(s), 1, fp);

printf("Want to enter another record(y/n): ");

fflush(stdin);
choice = getchar();

}
fclose(fp);

}

输出:

Enter name, rollno and percentage of student: jon
15
87.2
Want to enter another record(y/n): n

--------------------------------
Process exited after 6.154 seconds with return value 0
Press any key to continue . . .

“record.txt”文件的内容:

jon            ÿÿÿÿÿÿÿÿL              ù$@     L      ff®B

所以,我真正想知道的是,名字是按原样写的,但其他值(如 rollno 和百分比)看起来难以理解。为什么会这样?

PS 随意编辑问题的标题,因为我没有找到任何合适的标题。

标签: cstructurefile-handling

解决方案


这是固定代码:

# include<stdio.h>
# include<stdlib.h>

int main() {
    FILE *fp;
    char choice = 'y';

    struct student {
        char name[50];
        int rollno;
        float percentage;
    };
    struct student s;


    fp = fopen("record.txt", "w");
    if (fp == NULL) {
        puts("Unable to open the file");
        exit(0);
    }

    while (choice == 'y') {

        printf("Enter name, rollno and percentage of student: ");
        scanf("%50s %d %f", &s.name, &s.rollno, &s.percentage);

        fprintf(fp, "%s, %d, %f\n", s.name, s.rollno, s.percentage); // !changed

        printf("Want to enter another record(y/n): ");

        fflush(stdin);
        choice = getchar();

    }
    fclose(fp);

}

尤其是线路 fwrite(&s, sizeof(s), 1, fp);需要改变。

  • 用于fprintf()编写人类可读的数据
  • 您也不需要编写结构的位模式,而是访问结构的每个字段。

->fprintf(fp, "%s, %d, %f\n", s.name, s.rollno, s.percentage);

还有一件小事,如果你使用scanf("%50s %d %f", &s.name, &s.rollno, &s.percentage);你将读取的大小限制name为 50 个字符,防止缓冲区溢出。


推荐阅读