fread读取结构体

wzuxian2012 2012-06-23 09:30:46
size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );


这个函数, 的 第第2个参数是大小, 第三个是个数


1. 读取后一个结构后,如何解析????

struct MyStruct
{
int a;
char c;
};

如何解析???

2. 一个结构体存一行,会有换行,怎么处理
...全文
309 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2012-06-25
  • 打赏
  • 举报
回复
推荐使用WinHex软件查看文件或内存中的原始字节内容。

不要把
fopen("...","...");fscanf,fprintf,fclose //读时把\r\n替换成\n,写时把\n替换成\r\n;读到\x1a就设置EOF;读写的内容当字符看待

fopen("...","...b");fread,fwrite,fclose //不作以上替换,遇到\x1a仍继续读;读写的内容当字节看待
弄混了
qq120848369 2012-06-25
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 的回复:]

1. 为什么不处理换行

2. fread与二级制有什么关系,难道其他方式打开不行吗??

还是说,不一定非要是二进制
[/Quote]

在WINDOWS平台, 请严格区分文件格式是二进制文件还是文本文件。
pathuang68 2012-06-23
  • 打赏
  • 举报
回复
wzuxian2012 2012-06-23
  • 打赏
  • 举报
回复
有人回答3楼的问题吗
wzuxian2012 2012-06-23
  • 打赏
  • 举报
回复
1. 为什么不处理换行

2. fread与二级制有什么关系,难道其他方式打开不行吗??

还是说,不一定非要是二进制
qq120848369 2012-06-23
  • 打赏
  • 举报
回复
malloc一块内存, 然后fread进去一个结构体, 就可以用了.
quwei197874 2012-06-23
  • 打赏
  • 举报
回复
#include <stdio.h>
#define SIZE 2
struct student_type
{
char name[10];
int num;
int age;
char addr[10];
}stud[SIZE];
void save()
{
FILE *fp;
int i;
if((fp=fopen("stu_list","wb"))==NULL)
{
printf("cant open the file");
exit(0);
}
for(i=0;i<SIZE;i++)
{
if(fwrite(&stud[i],sizeof(struct student_type),1,fp)!=1)
printf("file write error\n");
}
fclose(fp);
}
main()
{
int i;
for(i=0;i<SIZE;i++)
{
scanf("%s%d%d%s",&stud[i].name,&stud[i].num,&stud[i].age,&stud[i].addr);
save();
}
for(i=0;i<SIZE;i++)
{
printf("%s,%d,%d",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
}
}

fread.c

#include <stdio.h>
#define SIZE 2
struct student_type
{
char name[10];
int num;
int age;
char addr[10];
}stud[SIZE];
void read()
{
FILE *fp;
int i;
if((fp=fopen("stu_list","rb"))==NULL)
{
printf("cant open the file");
exit(0);
}
for(i=0;i<SIZE;i++)
{
if(fread(&stud[i],sizeof(struct student_type),1,fp)!=1)
printf("file write error\n");
}
fclose(fp);
}
main()
{

int i;
read();
for(i=0;i<SIZE;i++)
{
printf("%s,%d,%d,%s",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
printf("\n");
}
}

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧