Fstream管理问题

Fstream management questions

我对如何使用 fstream 管理文件流有点困惑。我将在下面列出我的主要问题:

1) 首先,为什么调用构造函数 fstream file(file_name);fstream file; file.open(file_name); 而没有任何标志,如 ios::inios::out 不会创建任何新文件?

2) 假设我想使用同一个文件进行输入和输出。我可以做类似 fstream file 的事情,然后在需要单独使用它进行输出或输入操作时调用 file.open(file_name, ios::out)file.open(file_name, ios::in) 。但是如果我需要同时进行输入和输出怎么办?例如,我需要从文件中读取并在读取时发现特定的单词或数字时替换一行或一个字符。是否可以为已创建的文件调用 file.open(file_name)(并且不指定任何标志)?它允许我对同一流进行 read/write 操作吗?

使用 ifstream 和 ofstream 非常可行:

#include <fstream>
using namespace std;

int main() {
  ifstream source("source-file.txt");
  ofstream destination("source-file.txt");
  int x; // 0                                                                                                                   
  int y = 1;
  source >> x; // Reads one int from source-file.txt                                                                            
  source.close(); // Always close file when finished                                                                            
  destination << y; // Write to source-file.txt                                                                                 
  return 0;
} // destination.close() called by destructor

将溪流想象成一根稻草。你不能一边喝一边对着吸管吹气。喝一口,停下来,吹回去,重复。

这是我的答案:

1) First of all, why calling the constructors fstream file(file_name); or fstream file; file.open(file_name); without any flag like ios::in or ios::out doesn't create any new file?

在发生写操作之前不需要创建文件。这是延迟处理。

不需要创建文件,默认可能是用read权限打开文件。据我所知,以只读方式打开文件永远不会创建文件。

阅读这些案例的默认模式。

2) Let's say i want to use the same file for input and output. I can do something like fstream file and then call file.open(file_name, ios::out) or file.open(file_name, ios::in) when I need to use it for output or input operation separately. But what if I need to do input and output at the same time?

如果需要对同一个文件进行读写操作,请同时使用ios::inios::out两种方式打开:ios::out | ios::in。这是通知您要使用相同的流(文件)写入和读取的流。至少从 C 语言被发明以来,这是允许的。

顺便说一句,你应该澄清一下 "at the same time"。大多数事情在计算机上都是顺序的,除非涉及多个处理器(内核)。大多数文件是顺序的,这意味着只有一个源可以读取或写入文件。尽管有一些例外。

许多文件已被视为数组。您可以多次阅读和编写同一部分。这称为 随机访问 而不是 sequential access 的设备。