ubuntu

Ubuntu C++文件操作方法

小樊
41
2025-06-24 01:57:42
栏目: 编程语言

在 Ubuntu 系统中,C++ 文件操作主要通过 C++ 标准库 <fstream> 提供的功能来实现。以下是一些常用的文件操作方法:

1. 包含头文件

首先,确保在你的代码中包含了 <fstream> 头文件:

#include <fstream>

2. 打开文件

使用 std::ifstreamstd::ofstreamstd::fstream 来打开文件。

std::ifstream inputFile("example.txt");
if (!inputFile.is_open()) {
    std::cerr << "Unable to open file for reading!" << std::endl;
    return 1;
}
std::ofstream outputFile("output.txt");
if (!outputFile.is_open()) {
    std::cerr << "Unable to open file for writing!" << std::endl;
    return 1;
}
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;
}

3. 读取文件内容

可以使用 >> 操作符或 std::getline() 函数来读取文件内容。

std::string word;
while (inputFile >> word) {
    std::cout << word << std::endl;
}
std::string line;
while (std::getline(inputFile, line)) {
    std::cout << line << std::endl;
}

4. 写入文件内容

可以使用 << 操作符将数据写入文件。

outputFile << "Hello, World!" << std::endl;

5. 关闭文件

文件操作完成后,确保关闭文件以释放资源。

inputFile.close();
outputFile.close();
file.close();

6. 文件状态检查

可以使用成员函数来检查文件流的状态:

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 的文件用于写入。它逐行读取源文件的内容并将其写入目标文件。完成后,关闭两个文件并输出成功消息。

0
看了该问题的人还看了