fstream unix problem in reading

﹥>﹥吖頭↗ 提交于 2019-12-10 21:51:47

问题


I am trying to read from binary file on UNIX. The file exists and has several data information in it.

The code looks like this:

fstrean fstrHandler;

string strFileName;

char Buf[30000];

fstrHandler.open(strFileName.c_str(), ios::in | ios::binary);

fstrHandler.seekp(0, std::ios_base::beg);

std::cout<< "Posi before read= "<< fstrHandler.tellg()<<endl; //*** Show after running 0

fstrHandler.read (Buf, 400);

std::cout<< "Posi after read= "<< fstrHandler.tellg()<<endl; //*** Show after running 0

std::cout<< " gcount ()= "<< fstrHandler.gcount ()<< << endl; //*** Show after running 0

if (fstrHandler.eof ()) {
       fstrHandler.clear();
}

After the read I get that the position in file is still zero zero, but the file is not empty.


回答1:


Try seekg rather than seekp, and is there 400 bytes in the file? this appears to work okay for me, if you input a file that contains more than 400 bytes. If less, then the tellg after read reports -1, but gcount() is correct.

Also, after opening the file - test to see if the file was indeed opened e.g.

if (fstrHandler)
{
// do stuff
}
else
  std::cerr << "foo bar" << std::endl;


来源:https://stackoverflow.com/questions/4874530/fstream-unix-problem-in-reading

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!