Ubuntu中C++如何进行文件操作

194
2025/4/12 9:32:35
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Ubuntu中,C++可以使用标准库中的<fstream>来进行文件操作。以下是一些基本的文件操作示例:

  1. 包含头文件
#include <iostream>
#include <fstream>
#include <string>
  1. 创建一个文件并写入数据
void writeFile(const std::string& filename) {
    // 创建一个输出文件流对象
    std::ofstream outFile(filename);

    // 检查文件是否成功打开
    if (!outFile.is_open()) {
        std::cerr << "Error: Unable to open file for writing." << std::endl;
        return;
    }

    // 写入数据到文件
    outFile << "Hello, World!" << std::endl;
    outFile << "This is a test file." << std::endl;

    // 关闭文件
    outFile.close();
}
  1. 从一个文件读取数据
void readFile(const std::string& filename) {
    // 创建一个输入文件流对象
    std::ifstream inFile(filename);

    // 检查文件是否成功打开
    if (!inFile.is_open()) {
        std::cerr << "Error: Unable to open file for reading." << std::endl;
        return;
    }

    // 从文件读取数据
    std::string line;
    while (std::getline(inFile, line)) {
        std::cout << line << std::endl;
    }

    // 关闭文件
    inFile.close();
}
  1. 追加数据到一个文件
void appendFile(const std::string& filename) {
    // 创建一个输出文件流对象,并以追加模式打开文件
    std::ofstream outFile(filename, std::ios::app);

    // 检查文件是否成功打开
    if (!outFile.is_open()) {
        std::cerr << "Error: Unable to open file for appending." << std::endl;
        return;
    }

    // 追加数据到文件
    outFile << "This is an appended line." << std::endl;

    // 关闭文件
    outFile.close();
}
  1. 删除一个文件
void deleteFile(const std::string& filename) {
    if (std::remove(filename.c_str()) != 0) {
        std::cerr << "Error: Unable to delete the file." << std::endl;
    }
}
  1. 检查文件是否存在
bool fileExists(const std::string& filename) {
    std::ifstream inFile(filename);
    return inFile.good();
}

这些示例展示了如何在Ubuntu中使用C++进行基本的文件操作。你可以根据需要修改和扩展这些示例。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: ubuntu如何安装js环境