关于fread
假如a.txt里的内容如下:
12343109TP4562012-1-1
4565310703.652012-1-5
下面的代码会输出一些乱码,求指点!
- C/C++ code
#include<cstdlib>#include<iostream>using namespace std;struct Stu{ char ZH[15]; char XH[15]; char SY[15]; char SJ[15]; };typedef struct Node{ Stu stu; struct Node *next;}*No;int main(){ FILE *in; if((in=fopen("C:\\Users\\Jack\\Desktop\\a.txt","r"))==NULL){ printf("cannot open this file\n"); system("pause"); exit(0); } No p=(Node*)malloc(sizeof(Node)); p->next=NULL; No ip=p; while(!feof(in)){ No temp=(No)malloc(sizeof(Node)); fread(&(temp->stu),sizeof(Stu),1,in); temp->next=NULL; ip->next=temp; ip=temp; } fclose(in); for(ip=p->next;ip;ip=ip->next){ cout<<ip->stu.ZH; cout<<ip->stu.XH; cout<<ip->stu.SY; cout<<ip->stu.SJ; } system("pause"); return 0;}
[解决办法]
不能把stu的内容一股脑儿往文件里写。因为结构体里面的成员虽然有15个字符,但一般情况下都是读到0即停止,后面的内容都是未初始化过的。
[解决办法]
不要把
fopen("...","...");fscanf,fprintf,fclose //读时把\r\n替换成\n,写时把\n替换成\r\n;读到\x1a就设置EOF;读写的内容当字符看待
和
fopen("...","...b");fread,fwrite,fclose //不作以上替换,遇到\x1a仍继续读;读写的内容当字节看待
弄混了
[解决办法]