Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Binary File I/O

Options
  • 06-02-2006 2:40am
    #1
    Closed Accounts Posts: 1,061 ✭✭✭


    Ok I have the following piece of code:
    {
                    
                    cout << "Enter word: ";
                    cin.getline(word, 20);
                    
                    fstream fout("thisfile.this", ios::binary );
                    
        
                    fout.write((char *) word, sizeof(word));
                                
                    fout.read((char *)(&wword), sizeof(wword));
                   
                   
                    
                    cout << "word ENTERED: " << wword << endl;
                    
    
                    fout.flush();
                    fout.close();
                    
                    cin.get();
    }
    

    Now see screenshot for what i get..

    What am i doing wrong?


Comments

  • Registered Users Posts: 4,003 ✭✭✭rsynnott


    I'm assuming wword is actually a character string? That & probably shouldn't be there :)


  • Registered Users Posts: 1,481 ✭✭✭satchmo


    If you check fout.is_open(), you'll probably find it hasn't been opened properly. You need to specify ios::in | ios::out too because you've overridden the default parameter by specifying ios::binary. Similarly, you'll need to specify either ios::app or ios::trunc if the file doesn't already exist - if it does exist already then it'll be truncated by default.

    Then, after you've written to the file you'll need to reset the file pointer to the beginning of the file with fout.seekg(0, ios::beg);, otherwise all you're reading is data starting from after where you wrote to (which probably doesn't exist, which explains the garbage output).

    Like rsynnott said, that & probably shouldn't be there. It'll work in this case because wword is a pointer to an array and so saying &wword is the same as saying &wword[0], which is the address of the first variable in the array and so the same address as the pointer. But doing that to a regular pointer would get the address of the pointer variable, not the address that the pointer is pointing to.


Advertisement