c++文本文件讀寫(xiě)的方法是什么

c++
小億
102
2023-12-07 20:10:04

在C++中,文本文件的讀寫(xiě)可以使用標(biāo)準(zhǔn)庫(kù)中的fstream類。fstream類提供了與文件的輸入和輸出操作相關(guān)的成員函數(shù)和操作符重載。

以下是一些常用的文本文件讀寫(xiě)操作方法:

  1. 打開(kāi)文件: 可以使用fstream類的open函數(shù)來(lái)打開(kāi)文件。open函數(shù)接受兩個(gè)參數(shù):文件名和打開(kāi)模式(輸入、輸出或者輸入輸出)。
#include <fstream>
using namespace std;

int main() {
    ofstream file;
    file.open("example.txt"); // 打開(kāi)文件example.txt
    // 或者
    // ofstream file("example.txt");
    
    // 寫(xiě)入操作...
    
    file.close(); // 關(guān)閉文件
    
    return 0;
}
  1. 寫(xiě)入文件: 使用ofstream類對(duì)象的<<操作符可以將數(shù)據(jù)寫(xiě)入文件??梢韵袷褂胏out對(duì)象一樣使用ofstream對(duì)象。
#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類對(duì)象的>>操作符可以從文件中讀取數(shù)據(jù)。可以像使用cin對(duì)象一樣使用ifstream對(duì)象。
#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;
}

以上是一些基礎(chǔ)的文本文件的讀寫(xiě)方法,你可以根據(jù)需要進(jìn)一步探索fstream類提供的其他成員函數(shù)和操作符重載。

0