• C++ Tutorials: C++ Language: Standard library: Input/output with files


    C++官网参考链接:https://cplusplus.com/doc/tutorial/files/

    输入/输出文件
    C++提供了以下类来执行向文件输出和从文件中输入字符
    *ofstream(ofstream:写入文件中的流类
    *ifstream(ifstream:从文件中读取的流类
    *fstream(fstream:从文件中读取和写入到文件中的流类。 
    这些类直接或间接地派生自类istreamostream。我们已经使用过这些类类型的对象:cinistream类的对象,coutostream类的对象。因此,我们已经使用了与文件流相关的类。事实上,我们可以像使用cincout一样使用文件流,唯一不同的是我们必须将这些流与物理文件关联起来。让我们看一个例子:
    // basic file operations
    #include
    #include
    using namespace std;

    int main () {
      ofstream myfile;
      myfile.open ("example.txt");
      myfile << "Writing this to a file.\n";
      myfile.close();
      return 0;
    }

     

    这段代码创建了一个名为example.txt的文件,并以与cout相同的方式在其中插入一句话,但使用的是文件流myfile
    但让我们一步一步来: 

    打开一个文件
    对这些类的对象执行的第一个操作通常是将其关联到一个真实文件。这个过程被称为打开文件。一个打开的文件在程序中由一个表示(即,这些类中的一个对象;在前面的例子中,这是myfile),对这个对象执行的任何输入或输出操作都将应用到与它关联的物理文件。 
    为了打开带有流对象的文件,我们使用它的成员函数open
    open (filename, mode);
    其中filename是表示要打开的文件名的字符串,mode是一个可选形参,由以下标志的组合组成:

    ios::in Open for input operations.
    ios::out Open for output operations.
    ios::binary Open in binary mode.
    ios::ate

    Set the initial position at the end of the file.
    If this flag is not set, the initial position is the beginning of the file.

    (设置文件结束处的初始位置。如果未设置此标志,则初始位置为文件的开始。)

    ios::app

    All output operations are performed at the end of the file, appending the content to the current content of the file.

    (所有输出操作都在文件结束处执行,将内容追加到文件的当前内容。)

    ios::trunc
  • 相关阅读:
    每日一题 2258. 逃离火灾(手撕困难!!!)
    (黑马C++)L02 类 内联函数 函数重载
    总线、I/O总线、I/O接口
    嵌入式软件工程师面试题——2025校招专题(四)
    CAN总线协议测试拓扑图
    ad18学习笔记十一:显示和隐藏网络、铺铜
    【python】OpenCV—Tracking(10.2)
    一文讲明:企业知识库的作用和搭建方法
    java 取list 前几条,限制list长度
    【PAT甲级 - C++题解】1103 Integer Factorization
  • 原文地址:https://blog.csdn.net/weixin_40186813/article/details/126918127