2016-04-03 72 views
-2

我需要打開一個使用fstream進行讀/寫的文件並讀取每個字符,然後將該字符寫回文件。例如我有這個代碼。用於讀寫的C++文件流

fstream in("test.txt",ios::in | ios::out); 
if(!in) 
    cout<<"error..."; 
else 
{ 
    char ch; 
    in.seekg(0,ios::end); 
    int end=in.tellg();//get the length 

    in.seekg(0);//get back to the start 
    for(int i=0;i<end;i++) 
    { 
     //in.seekg(in.tellg());//if i uncomment this the code will work 
     if(!in.get(ch).fail())//read a character 
     { 
      in.seekp(static_cast<int>(in.tellg())-1);//move the pointer back to the previously read position,so i could write on it 
      if(in.put(ch).fail())//write back,this also move position to the next character to be read/write 
       break;//break on error 
     } 
    } 
} 

我有一個名爲"test.txt"的文件,其中包含「ABCD」。據我瞭解,流對象的方法put()get()都將文件指針向前移動(我通過在方法調用每個get()put()方法調用後獲得返回值tellg()tellp()函數)。我的問題是,當我註釋掉代碼將查找流指針「現在它在哪裏」(in.seekg(in.tellg())時,代碼將導致不正確的結果。我不明白爲什麼這是因爲tellg()顯示接下來要閱讀的角色的正確位置。明確尋求它的目的是什麼?我正在使用visual studio 2005.

不正確的結果是寫入文件「ABBB」而不是「ABCD」。

+0

你爲什麼要搞這個「尋找」業務呢? – ForceBru

+0

究竟「錯誤」結果如何? – mazhar

+0

'tellg()'返回'streampos',而不是'int'。你的「不正確」結果是什麼? –

回答

0

在寫入和讀取之間切換時,輸出緩衝區必須刷新。

fstream in("test.txt",ios::in | ios::out); 
if(!in) 
    cout<<"error..."; 
else 
{ 
    char ch; 
    in.seekg(0,ios::end); 
    int end=in.tellg();//get the length 

    in.seekg(0);//get back to the start 
    for(int i=0;i<end;i++) 
    { 
     if(!in.get(ch).fail())//read a character 
     { 
      in.seekp(static_cast<int>(in.tellg())-1);//move the pointer back to the previously read position,so i could write on it 
      if(in.put(ch).fail())//write back,this also move position to the next character to be read/write 
      break;//break on error 

      in.flush(); 
     } 
    } 
}