同时读取和写入文件? [英] Reading and writing to files simultaneously?

查看:447
本文介绍了同时读取和写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此处移动了问题。假设,我想存储1,000,000,000整数,不能使用我的记忆。我会使用一个文件(它可以轻松处理这么多的数据)。
我如何让它读写的同时。
使用 fstream文件(file.txt,ios :: out | ios :: in); 首先不创建文件。
我的意思是这样:
让文件的内容为 111111
然后,如果我运行: -

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

文件的内容不应为 101010 ?读取一个字符然后用0覆盖下一个字符或者将整个内容立即读入某个缓冲区,应该在文件中没有至少一个0? 1111110
但是内容保持不变,请解释。
谢谢。

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.

推荐答案

保持两个指针,一个读和一个写。如果您正在进行读/写操作,则需要使用 seeg seekp 成员函数显式设置这些指针。你还会发现,做格式化的I / O可能会干扰你想要做的事情,所以你应该使用 get / put 读取 / 写入

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.

另请参见 http: //stackoverflow.com/questions/2305480/why-cant-i-read-and-append-with-stdfstream-on-mac-os-x 了解有关fstreams开放模式的更多信息。

See also http://stackoverflow.com/questions/2305480/why-cant-i-read-and-append-with-stdfstream-on-mac-os-x for more on open modes with fstreams.

这篇关于同时读取和写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆