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

时间:2018-10-18 16:04:25

标签: c structure file-handling

出于学习目的,我正在将学生记录写入名为“ 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和percent)看起来难以理解。为什么会这样?

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

1 个答案:

答案 0 :(得分:1)

这是固定代码:

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