溫馨提示×

c++文本文件讀寫的方法是什么

c++
小億
109
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類對象的<<操作符可以將數據寫入文件??梢韵袷褂胏out對象一樣使用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類對象的>>操作符可以從文件中讀取數據??梢韵袷褂胏in對象一樣使用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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女