c语言文件操作fwrite和fread

#include<stdio.h>
#include<stdlib.h>
struct student
{
char name[10];
char num[10];
int score[3];
float aver;
}stud[5];
void main()
{
FILE *fp1;
int j=0;
if((fp1=fopen("d:\\test\\1.txt","rb"))==NULL)
{printf("Wrong!");exit(0);}
while(!feof(fp1))
{
fread(&stud[j],sizeof(struct student),1,fp1);
//输出
j++;
}
}
d:\test\1.txt中文件为:
jim 001 12 34 45 30.333333
kate 002 23 34 45 34.000000
tom 003 44 55 66 55.000000
lucy 004 55 66 66 62.333333
uuu 005 45 65 45 51.666667
问题是输出处用:fwrite(&stud[j],sizeof(struct student),1,stdout);正确
用: printf("%s %s %d %d %d %f\n",stud[j].name,stud[j].num,stud[j].score[0],stud[j].score[1],stud[j].score[2],stud[j].aver);则输出出错,
怎么回事这是 ,谢谢

fread是C语言标准为中的一个函数。它从一个文件流中读数据,最多读取count个元素,每个元素size字节,如果调用成功返回实际读取到的元素个数,如果不成功或读到文件末尾返回 0。

fwrite是C语言标准库中的一个函数,指向文件写入一个数据块。示例如下:

//读取一个完整的文件
#include <stdio.h>
#include <stdlib.h>
int main()
{
    FILE* pFile;   //文件指针
    long lSize;   // ç”¨äºŽæ–‡ä»¶é•¿åº¦
    char* buffer; // æ–‡ä»¶ç¼“冲区指针
    size_t result;  // è¿”回值是读取的内容数量
    pFile = fopen("myfile.bin" , "rb");
    if (pFile == NULL) {fputs("File error", stderr); exit(1);}    // å¦‚果文件错误,退出1
    // èŽ·å¾—文件大小
    fseek(pFile , 0 , SEEK_END); // æŒ‡é’ˆç§»åˆ°æ–‡ä»¶æœ«ä½
    lSize = ftell(pFile);  // èŽ·å¾—文件长度
    rewind(pFile);  // å‡½æ•°rewind()把文件指针移到由stream(流)指定的开始处, åŒæ—¶æ¸…除和流相关的错误和EOF标记
    // ä¸ºæ•´ä¸ªæ–‡ä»¶åˆ†é…å†…存缓冲区
    buffer = (char*) malloc(sizeof(char) * lSize); // åˆ†é…ç¼“冲区,按前面的 lSize
    if (buffer == NULL) {fputs("Memory error", stderr); exit(2);}  // å†…存分配错误,退出2
    //  è¯¥æ–‡ä»¶å¤åˆ¶åˆ°ç¼“冲区
    result = fread(buffer, 1, lSize, pFile); // è¿”回值是读取的内容数量
    if (result != lSize) {fputs("Reading error", stderr); exit(3);} // è¿”回值如果不和文件大小,读错误
 
    // terminate // æ–‡ä»¶ç»ˆæ­¢
    fclose(pFile);
    free(buffer);
    return 0;
}

综合使用的例子。

#include <stdio.h>
int main()
{
    FILE* pFile;
    float buffer[] = { 2.0 , 3.0 , 8.0 };
    pFile = fopen("myfile.bin" , "wb"); // æ‰“开文件写操作
    fwrite(buffer , 1 , sizeof(buffer) , pFile); // æŠŠæµ®ç‚¹æ•°ç»„写到文件 myfile.bin
    fclose(pFile); // å…³é—­æ–‡ä»¶
    float read[3];
    pFile = fopen("myfile.bin" , "rb"); // é‡æ–°æ‰“开文件读操作
    fread(read , 1 , sizeof(read) , pFile); // ä»Žæ–‡ä»¶ä¸­è¯»æ•°æ®
    printf("%f\t%f\t%f\n", read[0], read[1], read[2]);
    fclose(pFile); // å…³é—­æ–‡ä»¶
    return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-09-14
无语的写法..
你根本分不清什么事数字 什么事字符

如果你要输出txt里面的内容比较简单.

char buf[1024];

fread(&stud[j],sizeof(struct student),1,fp1);
改成
fread(buf,1024,1,fp1);

printf 改成 printf(%s, buf);

如果你要把 txt里面的字符变成数据.
那就需要解析txt了
第2个回答  2009-09-16
读了你的代码,我觉得,你在用fread的时候,其实你的意图是想将1.txt中的每一行按照你所定义的structure student中的字段格式,进行读取,将你的stud一个一个填充好。很遗憾,fread并不能做这件事情。fread会将1.txt中的每行看做一整个字符串,写到你给的每个&stud[j]开头的地址空间中,而无视你所给定的structure的定义,自然你printf就得不到预想的结果了。而fwrite倒是可以原原本本将写入的字串回写出来。
如果你想要按structure的格式读入1.txt的数据,那么就要用scanf咯。就像printf那样,scanf的用法你一定是懂的。本回答被提问者采纳
相似回答