c - 如何将 fread() 2 个结构放在一起 C
问题描述
如何fread()
在 1 行中显示 2 个语句。
这是我的代码的一部分:
FILE *fp;
fp = fopen("hello", "rb");
struct clientName NAME;
struct clientAge AGE;
system("cls");
if(fp == NULL){
printf("ERROR");
getch();
}
else{
printf("NAME\t\tAGE\n");
printf("-----------------------------------------\n");
while((fread((char *)&NAME, sizeof(struct clientName), 1, fp))==1){
printf("%s", NAME.name);
while((fread((char *)&AGE, sizeof(struct clientAge), 1, fp))==1){
printf("\t\t%d", AGE.age);
}
}
当有 1 组数据时,格式正确。但是当有 2 组或更多组数据时,它开始变得混乱。我对 C 中的文件处理真的很陌生。谢谢!
解决方案
假设您的文本格式如下。
name1
age1
name2
age2
在这种情况下,您需要的是。
while((fread((char *)&NAME, sizeof(struct clientName), 1, fp))==1 &&
(fread((char *)&AGE, sizeof(struct clientAge), 1, fp))==1){
printf("%s", NAME.name);
printf("\t\t%d", AGE.age);
}
推荐阅读
- google-apps-script - 有没有办法使用 Google People API 将用户名提取到 Google 表单中?
- ios - 更改单元格高度后单元格文本标签未居中
- javascript - 使用 Socket.io 发送和接收数据
- javascript - Vue 事件处理程序,在所有组件之间共享
- c - 如何修复“I/O 警告:无法加载外部实体“file.xml””?libxml2,macOS
- php - 如何使用数组中的元素在 PHP 中打印文本文件
- c++ - C++中的二维向量数组
- css - 禁用 Material UI 默认样式
- php - 错误计数 php date_diff
- laravel-5 - 我想从控制器中的 ajax 请求到模块中生成具有其值的新列