2011-04-17 73 views
0

我嘗試打開一個讀寫的二進制文件(標誌:ios_base :: binary | ios_base :: in | ios_base :: out)。使用C++編寫二進制文件時出錯

我的文件已經存在,其內容爲:123

有一個在文件的閱覽沒問題,但寫入文件關閉文件後,無法正常工作。文件內容沒有變化。看來fstream.write()無法正常工作。

我使用VS2010。

代碼:

#include <iostream> 
#include <fstream> 
using namespace std; 

int main (void) 
{ 
    fstream stream; 

    // Opening the file: binary + read + write. 
    // Content of file is: 123 
    stream.open("D:\\sample.txt", ios_base::binary | ios_base::in | ios_base::out); 

    // Read 1 bye. 
    char ch; 
    stream.read(&ch, 1/*size*/); 

    // Check any errors. 
    if(!stream.good()) 
    { 
     cout << "An error occured." << endl; 
     return 1; 
    } 

    // Check ch. 
    // Content of file was: 123 
    if(ch == '1') 
    { 
     cout << "It is correct" << endl; 
    } 

    // Write 1 bye. 
    ch = 'Z'; 
    stream.write(&ch, 1/*size*/); 

    // Check any errors. 
    if(!stream.good()) 
    { 
     cout << "An error occured." << endl; 
     return 1; 
    } 

    // Close the file. 
    stream.close(); 

    // OHhhhhhhhhhh: 
    // The content of file should be: 1Z3 
    // but it is: 123 

    return 0; 
} 

感謝。

對不起,我的英語pooooooor :-)

回答

3

你需要放置寫指針correcty:

stream.seekp(1); 
stream.write(&ch, 1/*size*/); 
+0

是的!它工作:)但爲什麼? – 2011-04-17 11:46:18

+0

是的,我也想知道,不'stream.read()'已經移動指針了嗎? – orlp 2011-04-17 11:49:46

+1

只有一個文件位置,在讀寫之間共享。因此,每次更改模式時都必須定位它。 – 2011-04-17 11:56:03