文件的读写问题?我觉得挺有意思的一个问题

MZJCDD 2008-06-10 05:43:36
假如一个文件F:\\ABC\\jz0214.txt里面存有这样的数据
学号 姓名 c语言 高数 线性代数
14 名在 88.0 66.0 99.0
12 我自己 99.0 99.0 99.0
16 服务机构 99.0 99.0 93.0
#include<stdio.h>
#include<stdlib.h>
struct student
{
char xuehao[10];
char name[10];
float score[3];
}stu[3];
void main()
{
FILE *fp;
if((fp=fopen("F:\\ABC\\jz0214.txt","r"))==NULL)
{
printf("can't open the file:");
exit(0);
}
for(int i=0;i<3;i++)
fread(&stu[i],sizeof(stu[i]),1,fp);
fclose(fp);
printf("%s",stu[1].name);
}
为什么我想打印出来“我自己”,为什么跟想象的不一样
...全文
158 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
不一定非要二进制读写……
一般只要读和写方式相同即可,要么都是文本读写,要么都是二进制读写……
yuzl32 2008-06-10
  • 打赏
  • 举报
回复
采用整个结构写入和读出!

#include <stdio.h>
#include <string.h>

struct student
{
char xuehao[10];
char name[10];
float score[3];
} stu[3];


int main( void )
{
FILE *stream;
int numwritten,numread;
student stu2[3];

//initialize data
strcpy(stu[0].xuehao,"14");
strcpy(stu[1].xuehao,"12");
strcpy(stu[2].xuehao,"16");

strcpy(stu[0].name,"名在");
strcpy(stu[1].name,"我自己");
strcpy(stu[2].name,"服务机构");

stu[0].score[0] = 88.0f;
stu[0].score[1] = 66.0f;
stu[0].score[2] = 99.0f;

stu[1].score[0] = 99.0f;
stu[1].score[1] = 99.0f;
stu[1].score[2] = 99.0f;

stu[2].score[0] = 99.0f;
stu[2].score[1] = 99.0f;
stu[2].score[2] = 93.0f;

// Open file in text mode:
if( (stream = fopen("fread.out", "w+t" )) != NULL)
{
// Write 25 characters to stream
numwritten = fwrite( stu, sizeof( student ), 3, stream );
printf( "Wrote %d items\n", numwritten );
fclose( stream );

}
else
printf( "Problem opening the file\n" );

if( (stream = fopen("fread.out", "r+t" )) != NULL )
{
// Attempt to read in 25 characters
numread = fread( stu2, sizeof( student ), 3, stream );
printf( "Number of items read = %d\n", numread );
printf( "My name is = %s\n", stu2[1].name );
fclose( stream );
}
else
printf( "File could not be opened\n" );
}

/out:Client.exe
Client.obj

E:\>Client
Wrote 3 items
Number of items read = 3
My name is = 我自己
飞哥 2008-06-10
  • 打赏
  • 举报
回复
说的都有道理
stars_eyes 2008-06-10
  • 打赏
  • 举报
回复
1、如果要以文本方式进行操作,可以考虑用fscanf和fprintf函数读、写文件,但比较麻烦,效率也比较低
2、换用fread和fwrite函数,以二进制方式进行操作
猪翼天翔 2008-06-10
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 davelv 的回复:]
首先fread是以二进制格式读取文件的,但是你没有使用"rb"参数,还有,你的txt文件也是用字符型格式存储的,所以会出现错误
如果楼主想得到自己的结果,先用生成一个二进制文件,用fwrite函数写进去,再用fread函数读入就可以了~
[/Quote]
up
unixzyy 2008-06-10
  • 打赏
  • 举报
回复
用结构加上fread与fwrite读写.
如果是文本,则要fgets()后进行拆分.
ysuliu 2008-06-10
  • 打赏
  • 举报
回复
学习
davelv 2008-06-10
  • 打赏
  • 举报
回复
首先fread是以二进制格式读取文件的,但是你没有使用"rb"参数,还有,你的txt文件也是用字符型格式存储的,所以会出现错误
如果楼主想得到自己的结果,先用生成一个二进制文件,用fwrite函数写进去,再用fread函数读入就可以了~

69,371

社区成员

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

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