【问题标题】:What is the difference between ifstream, ofstream and fstream? [duplicate]ifstream、ofstream 和 fstream 有什么区别? [复制]
【发布时间】:2021-05-21 05:10:53
【问题描述】:

在文件处理中,我遇到过ifstream、ofstream 和fstream。谁能告诉我这些之间的主要区别?

【问题讨论】:

标签: c++ fstream ifstream ofstream


【解决方案1】:

ifstream 仅用于输入。

ofstream 仅用于输出。

fstream 可用于输入和/或输出。

【讨论】:

    【解决方案2】:

    这是类层次结构的样子: 来自https://www.cplusplus.com/img/iostream.gif

    处理文件处理的三个类是:

    • basic_ifstream
    • basic_ofstream
    • basic_fstream

    ifstreamofstreamfstream 是“chartemplate specializations,这意味着它们只不过是 basic_ifstream<char>basic_ofstream<char>basic_fstream<char>,即它们处理阅读和写作 char s 来自一个文件。

    • ifstream 是输入文件流,允许您读取文件的内容。
    • ofstream 是输出文件流,允许您将内容写入文件。
    • fstream 默认允许读取和写入文件。但是,您可以通过传入ios::open_mode 标志让fstream 表现得像ifstreamofstream

    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 组合用于 ifstreamios::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
    

    基本上可以永远不要使用ifstreamofstream,而总是使用带有所需标志的fstream。但是在设置标志时很容易出现意外错误。因此,使用ifstream 可以确保永远不会发生写入,而使用ofstream 只会发生写入。

    【讨论】:

    • 最后一句应修改为:因此,使用 ifstream 可以确保始终启用读取,而无需使用(或不使用)任何掩码。以此类推,ofstream 将始终启用写入。
    【解决方案3】:

    关键在名字中:

    • ifstream = "输入文件流" 这是istream 或 "输入流" 的一种类型
    • ofstream = "输出文件流" 这是ostream 的一种类型或"输出流"
    • fstream = "(双向) 文件流" 如iostream ("输入/输出流") 如includes both aspects 通过继承

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-03
      • 1970-01-01
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-28
      相关资源
      最近更新 更多