By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,617 Members | 1,600 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,617 IT Pros & Developers. It's quick & easy.

Read/write problem using fstream in binary mode.

P: 21
I have a binary file,which contains strings of 30 bytes each.I need to open the file,read the strings one by one and if the string is not found i need to write it.But unfortunately both read and write using fstream is not not working.If i close the file and open it again it works.

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <sys/stat.h>
  3. #include <fstream>
  4.  
  5. int main(){
  6. fstream fs;
  7. char write[30]= {"A0000.label"};
  8. char read[30];
  9. struct stat sb;
  10.  
  11.    if((stat ("test.txt",&sb)) > -1 )
  12.     {
  13.      fs.open ("test.txt",ios::in|ios::out|ios::app|ios::binary);
  14.      fs.seekg (0,ios::beg);
  15.  
  16.       while(!fs.read ((char*)(&read),sizeof(read)).fail()){
  17.            if(!strncmp(write,read,30))
  18.            {
  19.             std::cout<<"found"<<std::endl;
  20.             return 1;
  21.            }
  22.      }
  23.  
  24.  fs.seekg (0,ios::end);
  25.  fs.write((char*)(&write),sizeof(write))         >>> Here write fails  
  26.  fs.close();
  27. }
  28. return 1;
  29. }
Oct 28 '06 #1
Share this Question
Share on Google+
1 Reply


Banfa
Expert Mod 5K+
P: 8,916
I think that when fs.read reaches the end of file it set's some sort of flag that causes all further file operations to fail.

You need to clear that flag before continuing and there is a member function to do that.
Nov 1 '06 #2

Post your reply

Sign in to post your reply or Sign up for a free account.