关于文件尾的问题?

bill1973 2005-05-14 11:44:24
我写作业的时候常要从文件中读数据。
片段如下

ifstream file("...");
while(file.good()){
file>>...
}

但是文件尾标志总是作为一个数据读入后才结束,所以我还得加一段判断数据,好难看。 不知各位有什么好招吗?
...全文
196 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
flying_dancing 2005-05-15
  • 打赏
  • 举报
回复
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream fin("input.dat");
char *s=new char [1024*1024];
int k=0;
while(fin.get(s[k++]))
s[k]='\0';
cout<<s<<endl;
fin.close();
system("PAUSE");
return 0;
}
bill1973 2005-05-15
  • 打赏
  • 举报
回复
我是用的c++ 在unix g++ 下编译,不是vc。

file.good() 是判断是否文件读完,这是文件流的一个函数,我看和file.eof 是一样的 (高手说一下有什么区别)

程序不出错,只是有点 ugly
bill1973 2005-05-15
  • 打赏
  • 举报
回复

ifstream file("MRO.dat");
if(!file){
cerr<<"unable to open: MRO.dat"<<endl;
return -1;
}
int counter=0; //number of customer
while(file.good()){
CPtr CurCPtr = new Customer;
CurCPtr->no = ++counter;
file >> CurCPtr->time;
file >> CurCPtr->surname;
file >> CurCPtr->transaction;
file >> CurCPtr->payment;

//check whether is end of file
if (CurCPtr->payment !='C' && CurCPtr->payment !='$'){
delete CurCPtr;
break;
}

//SignInQ.AddToTail(CurCPtr);
EPtr CurEvent = new Event;
CurEvent->cr = CurCPtr;
CurEvent->eventTime = CurCPtr->time;
CurEvent->nature = CUSTOMER_ARRIVAL;
EventQ.AddToTail(CurEvent);
}
file.close();
xuzheng318 2005-05-15
  • 打赏
  • 举报
回复
#include "stdio.h"
#include "string.h"
#define N 5

struct student
{
char NO[8];
char name[10];
}stu[N],stu2;

char s_NO[8];

void main()
{
FILE *fp;
fp=fopen("e:\\read.txt","wb");
int i;

printf("enter students info(3 people):\n");

for(i=0;i<3;i++)
{
scanf("%s %s",stu[i].NO,stu[i].name);
fwrite(&stu[i],sizeof(student),1,fp); /* 整个结构体写入 */
}

fclose(fp);

fp=fopen("e:\\read.txt","rb");
printf("enter search NO.:");
scanf("%s",s_NO);

int flag=0;

while(!feof(fp)) /* 是否到文件尾 */
{
fread(&stu2,sizeof(student),1,fp); /* 整个结构体读出 */
if (strcmp(stu2.NO,s_NO)==0)
{
printf("search success.\n"); /* 找到了 */
flag=1;
break;
}
}

if (flag==0)
printf("search failed.\n"); /* 未找到 */

fclose(fp);
}
bill1973 2005-05-15
  • 打赏
  • 举报
回复
强调一下:

我是想用 file>>... //因为我用它读数据而不是字符串,这样简洁

我希望解决的是不要下面一段的办法

/*check whether is end of file ,这一段是因为文件结束标志做为数据被读入了,产生一个假数据*/

if (CurCPtr->payment !='C' && CurCPtr->payment !='$'){
delete CurCPtr;
break;
}
llf_hust 2005-05-15
  • 打赏
  • 举报
回复
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream fin("input.dat");
char *s=new char [1024*1024];
int k=0;
while(fin.get(s[k++]))
; //这里应该加个分号吧
s[k]='\0';
cout<<s<<endl;
fin.close();
system("PAUSE");
return 0;
}

csolution 2005-05-14
  • 打赏
  • 举报
回复
file.good()? 请说详细一点,这样没有人能明白你说的。

64,702

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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