【发布时间】:2021-05-21 05:10:53
【问题描述】:
在文件处理中,我遇到过ifstream、ofstream 和fstream。谁能告诉我这些之间的主要区别?
【问题讨论】:
标签: c++ fstream ifstream ofstream
在文件处理中,我遇到过ifstream、ofstream 和fstream。谁能告诉我这些之间的主要区别?
【问题讨论】:
标签: c++ fstream ifstream ofstream
ifstream 仅用于输入。
ofstream 仅用于输出。
fstream 可用于输入和/或输出。
【讨论】:
这是类层次结构的样子: 来自https://www.cplusplus.com/img/iostream.gif
处理文件处理的三个类是:
basic_ifstreambasic_ofstreambasic_fstreamifstream、ofstream 和 fstream 是“char”template specializations,这意味着它们只不过是 basic_ifstream<char>、basic_ofstream<char> 和 basic_fstream<char>,即它们处理阅读和写作 char s 来自一个文件。
ifstream 是输入文件流,允许您读取文件的内容。ofstream 是输出文件流,允许您将内容写入文件。fstream 默认允许读取和写入文件。但是,您可以通过传入ios::open_mode 标志让fstream 表现得像ifstream 或ofstream。ios::openmode标志打开模式标志是:
| Flag | Description |
|---|---|
ios::app |
All write operations must occur at the end of the file |
ios::binary |
Open in binary mode |
ios::in |
Open for reading |
ios::out |
Open for writing |
ios::trunc |
Empty the contents of the file after opening |
ios::ate |
Go to the end of the file after opening |
这些标志是相加的,这意味着您可以使用按位 OR | 运算符组合多个标志。如果我想以二进制模式打开文件并追加,我可以组合标志如下:
ios::binary | ios::app
ifstream 始终设置了 ios::in 标志,并且无法将其删除。同样,ofstream 始终设置了 ios::out 标志,并且无法将其删除。添加的任何其他标志都将与 ios::in 组合用于 ifstream 和 ios::out 用于 ofstream
fstream 传递任何标志,则默认为ios::in | ios::out,因此您可以读取和写入文件。但是,如果您为fstream 明确指定一个标志,例如ios::in,它将只为读取而打开,例如ifstream。你可以在构造函数中或者在调用open()时这样做:
ifstream infile("filepath", ios::binary); //Open the file for reading in binary mode, ios::in will always be set
ofstream outfile("filepath", ios::trunc); // Open the file for writing and clear its contents, ios::out is implicitly set
fstream inoutfile("filepath") // default flag will be: ios::in | ios::out hence both reads and writes possible
fstream infile("filepath", ios::in) // file will be opened in read mode like fstream
基本上可以永远不要使用ifstream 和ofstream,而总是使用带有所需标志的fstream。但是在设置标志时很容易出现意外错误。因此,使用ifstream 可以确保永远不会发生写入,而使用ofstream 只会发生写入。
【讨论】:
关键在名字中:
ifstream = "输入文件流" 这是istream 或 "输入流" 的一种类型ofstream = "输出文件流" 这是ostream 的一种类型或"输出流"fstream = "(双向) 文件流" 如iostream ("输入/输出流") 如includes both aspects 通过继承【讨论】: