开发者

Reading and writing to files simultaneously?

开发者 https://www.devze.com 2022-12-29 11:00 出处:网络
Moved the question here. Suppose, I want to store 1,000,000,000 integers and cannot use my memory. I would use a file(which can easily handle so much data ).

Moved the question here. Suppose, I want to store 1,000,000,000 integers and cannot use my memory. I would use a file(which can easily handle so much data ). How can I let it read and write and the same time. Using fstream file("file.txt', ios::out | ios::in ); doesn't create a file, in the first place. But supposing the file exists, I am unable to use to do reading and writing simultaneously. WHat I mean is this : Let the contents of the file be 111111 Then if I run : -

#include <fstream>
#include <iostream>
using namespace std;
int main()
{
  fstream file("file.txt",ios:in|ios::out);
  char x;
  while( file>>x)
  {
    file<<'0';
  }
 return 0;
}

Shouldn开发者_运维知识库't the file's contents now be 101010 ? Read one character and then overwrite the next one with 0 ? Or incase the entire contents were read at once into some buffer, should there not be atleast one 0 in the file ? 1111110 ? But the contents remain unaltered. Please explain. Thank you.


The filestreams maintain two pointers, one of reading and one for writing. If you are doing read/write operations you need to set these pointers explicitly with the seeg and seekp member functions. You will also find that doing formatted I/O may interfere with what you are trying to do, so you should be using the get/put and read/write member functions instead.

See also Why can't I read and append with std::fstream on Mac OS X? for more on open modes with fstreams.


Two possible solutions which would be much more efficient: (i) use a 64-bit OS or (ii) use mmap.

% man mmap

0

精彩评论

暂无评论...
验证码 换一张
取 消