Read/write problem using fstream in binary mode.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vinothg
    New Member
    • Oct 2006
    • 21

    #1

    Read/write problem using fstream in binary mode.

    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.

    Code:
    #include <iostream>
    #include <sys/stat.h>
    #include <fstream>
    
    int main(){
    fstream fs;
    char write[30]= {"A0000.label"};
    char read[30];
    struct stat sb;
    
       if((stat ("test.txt",&sb)) > -1 )
        {
         fs.open ("test.txt",ios::in|ios::out|ios::app|ios::binary);
         fs.seekg (0,ios::beg);
    
          while(!fs.read ((char*)(&read),sizeof(read)).fail()){
               if(!strncmp(write,read,30))
               {
                std::cout<<"found"<<std::endl;
                return 1;
               }
         }
    
     fs.seekg (0,ios::end);
     fs.write((char*)(&write),sizeof(write))         [B]>>> Here write fails [/B] 
     fs.close();
    }
    return 1;
    }
    Last edited by Banfa; Nov 1 '06, 12:54 PM. Reason: Added [code]...[/code] round the code
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    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.

    Comment

    Working...