Ama*_*l K 21
类层次结构如下所示:
来自https://www.cplusplus.com/img/iostream.gif
处理文件处理的三个类是:
basic_ifstreambasic_ofstreambasic_fstreamifstream、ofstream和fstream是“ char”模板特化,这意味着它们只不过是 和,basic_ifstream<char>即它们处理从文件中读取和写入。basic_ofstream<char>basic_fstream<char>char
ifstream是输入文件流,它允许您读取文件的内容。ofstream是输出文件流,它允许您将内容写入文件。fstream默认情况下允许读取和写入文件。但是,您可以通过传入标志来实现fstream类似ifstreamor的行为。ofstreamios::open_modeios::openmode旗帜打开模式标志是:
| 旗帜 | 描述 |
|---|---|
ios::app |
所有写操作必须发生在文件末尾 |
ios::binary |
以二进制模式打开 |
ios::in |
开放阅读 |
ios::out |
开放写作 |
ios::trunc |
打开后清空文件内容 |
ios::ate |
打开后转到文件末尾 |
这些标志是可加的,这意味着您可以使用按位 OR 运算符组合多个标志|。如果我想以二进制模式打开文件并追加,我可以按如下方式组合标志:
ios::binary | ios::app
Run Code Online (Sandbox Code Playgroud)
ifstream始终ios::in设置该标志并且无法将其删除。类似地,ofstream始终ios::out设置该标志并且无法将其删除。ios::in添加的任何其他标志将与forifstream和ios::outfor组合ofstreamfstream,则默认值为ios::in | ios::out,因此您可以读取文件也可以写入文件。fstream但是,如果您为like显式指定一个标志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
Run Code Online (Sandbox Code Playgroud)
基本上可以从不使用ifstream和始终与所需的标志一起ofstream使用。fstream但在设置标志时很容易出现意外错误。因此,使用ifstream您可以确保永远不会发生写入,并且ofstream只会发生写入。
ios::noreplace)C++ 23 添加了ios::noreplace专门打开文件用于写入的标志。该标志已存在于某些实现中,但现在已在 C++ 23 中标准化。如果文件已存在,则无法打开。
| 归档时间: |
|
| 查看次数: |
25550 次 |
| 最近记录: |