reading/writing 的 C++ 文件流

C++ file stream for reading/writing

我需要使用 fstream 为 reading/writing 打开一个文件并读取每个字符,然后将该字符写回到文件中。例如我有这个代码。

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() 方法都将文件指针向前移动(我看到通过获取 tellg() 或 [=16= 的 return 值] 在每个 get()put() 方法调用之后起作用)。我的问题是,当我注释掉将寻找指向 "where it is now"(in.seekg(in.tellg()) 的流指针的代码时,该代码将导致不正确的结果。我不明白为什么这是因为 tellg() 显示要读取的字符的正确位置 next.what 是明确寻求它的目的?我正在使用 visual studio 2005。

不正确的结果是它写入文件 "ABBB" 而不是 "ABCD"。

在写入和读取之间切换时必须刷新输出缓冲区。

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();
      }
   }
}