在 Ubuntu 系统中,C++ 文件操作主要通过 C++ 标准库 <fstream> 提供的功能来实现。以下是一些常用的文件操作方法:
首先,确保在你的代码中包含了 <fstream> 头文件:
#include <fstream> 使用 std::ifstream、std::ofstream 或 std::fstream 来打开文件。
std::ifstream):std::ifstream inputFile("example.txt"); if (!inputFile.is_open()) { std::cerr << "Unable to open file for reading!" << std::endl; return 1; } std::ofstream):std::ofstream outputFile("output.txt"); if (!outputFile.is_open()) { std::cerr << "Unable to open file for writing!" << std::endl; return 1; } std::fstream):std::fstream file("data.txt", std::ios::in | std::ios::out); if (!file.is_open()) { std::cerr << "Unable to open file for reading and writing!" << std::endl; return 1; } 可以使用 >> 操作符或 std::getline() 函数来读取文件内容。
>> 操作符逐个读取单词:std::string word; while (inputFile >> word) { std::cout << word << std::endl; } std::getline() 读取整行:std::string line; while (std::getline(inputFile, line)) { std::cout << line << std::endl; } 可以使用 << 操作符将数据写入文件。
outputFile << "Hello, World!" << std::endl; 文件操作完成后,确保关闭文件以释放资源。
inputFile.close(); outputFile.close(); file.close(); 可以使用成员函数来检查文件流的状态:
eof():检查是否到达文件末尾。fail():检查是否发生错误。bad():检查是否发生不可恢复的错误。if (inputFile.eof()) { std::cout << "Reached end of file." << std::endl; } if (inputFile.fail()) { std::cerr << "An error occurred while reading the file." << std::endl; } 下面是一个简单的示例,演示如何读取一个文件并将其内容复制到另一个文件:
#include <iostream> #include <fstream> #include <string> int main() { std::ifstream inputFile("source.txt"); std::ofstream outputFile("destination.txt"); if (!inputFile.is_open() || !outputFile.is_open()) { std::cerr << "Error opening files!" << std::endl; return 1; } std::string line; while (std::getline(inputFile, line)) { outputFile << line << std::endl; } inputFile.close(); outputFile.close(); std::cout << "File copied successfully." << std::endl; return 0; } 这个程序打开一个名为 source.txt 的文件用于读取,创建并打开一个名为 destination.txt 的文件用于写入。它逐行读取源文件的内容并将其写入目标文件。完成后,关闭两个文件并输出成功消息。