温馨提示×

c++文本文件读写的方法是什么

c++
小亿
87
2023-12-07 20:10:04
栏目: 编程语言

在C++中,文本文件的读写可以使用标准库中的fstream类。fstream类提供了与文件的输入和输出操作相关的成员函数和操作符重载。

以下是一些常用的文本文件读写操作方法:

  1. 打开文件: 可以使用fstream类的open函数来打开文件。open函数接受两个参数:文件名和打开模式(输入、输出或者输入输出)。
#include <fstream>
using namespace std;

int main() {
    ofstream file;
    file.open("example.txt"); // 打开文件example.txt
    // 或者
    // ofstream file("example.txt");
    
    // 写入操作...
    
    file.close(); // 关闭文件
    
    return 0;
}
  1. 写入文件: 使用ofstream类对象的<<操作符可以将数据写入文件。可以像使用cout对象一样使用ofstream对象。
#include <fstream>
using namespace std;

int main() {
    ofstream file("example.txt");
    
    if (file.is_open()) {
        file << "Hello, World!" << endl;
        file << "This is a text file." << endl;
        
        file.close();
    }
    
    return 0;
}
  1. 读取文件: 使用ifstream类对象的>>操作符可以从文件中读取数据。可以像使用cin对象一样使用ifstream对象。
#include <fstream>
#include <iostream>
using namespace std;

int main() {
    ifstream file("example.txt");
    
    if (file.is_open()) {
        string line;
        while (getline(file, line)) {
            cout << line << endl;
        }
        
        file.close();
    }
    
    return 0;
}

以上是一些基础的文本文件的读写方法,你可以根据需要进一步探索fstream类提供的其他成员函数和操作符重载。

0