.txt 的内容看起来是乱码,其内容是使用 C 编写的

Contents of a .txt looks gibberish whose content is written using 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随意编辑问题的标题,因为我没有找到合适的标题。

这是固定码:

# 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 个字符,防止缓冲区溢出。