溫馨提示×

C++中怎么輸入輸出文件

c++
小億
138
2024-03-11 16:14:24
欄目: 編程語言

在C++中,可以使用ifstreamofstream來進行文件的輸入和輸出操作。

文件輸入操作示例:

#include <iostream>
#include <fstream>

int main() {
    std::ifstream inputFile("input.txt"); // 打開輸入文件

    if (inputFile.is_open()) {
        std::string line;
        while (std::getline(inputFile, line)) {
            std::cout << line << std::endl; // 輸出文件內容
        }
        inputFile.close(); // 關閉文件
    } else {
        std::cout << "Unable to open file" << std::endl;
    }

    return 0;
}

文件輸出操作示例:

#include <iostream>
#include <fstream>

int main() {
    std::ofstream outputFile("output.txt"); // 打開輸出文件

    if (outputFile.is_open()) {
        outputFile << "Hello, world!" << std::endl; // 寫入文件
        outputFile.close(); // 關閉文件
    } else {
        std::cout << "Unable to open file" << std::endl;
    }

    return 0;
}

以上示例演示了如何打開、讀取和寫入文件。在實際應用中,需要根據具體的需求進行文件操作,并注意及時關閉文件流。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女