c - .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 随意编辑问题的标题,因为我没有找到任何合适的标题。
解决方案
这是固定代码:
# 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 个字符,防止缓冲区溢出。
推荐阅读
- wordpress - 如果满足元数据的特定条件,是否可以在 Wodpress 中中止发布更新?
- javascript - 如何在 JQuery 中获取鼠标事件?
- azure - 从 Azure Functions node.js 调用 Azure SQL
- python - 由于德语变音符号,Python中的字符串不相等
- php - 如何设置 WordPress 导航系统的样式,使其看起来像这样?
- r - Access input ID of reactive radioButtons in shiny app
- sql-server - System.Data.SqlClient.SqlException:“将 varchar 值 'gcobani' 转换为数据类型 int 时转换失败。”
- linux - 使用 grep 时如何获取查询订单输出?
- python - 从 Jupyter Notebook 显示和保存 PGF 图
- node.js - npm install 完成时播放声音或通知