2011-04-17 75 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