ubuntu

Ubuntu C++文件操作技巧

小樊
46
2025-06-09 21:05:13
栏目: 编程语言

在Ubuntu环境下使用C++进行文件操作,你可以利用C++标准库中的<fstream>头文件提供的类和函数。下面是一些基本的文件操作技巧:

打开文件

使用std::ifstream打开文件进行读取,使用std::ofstream打开文件进行写入,使用std::fstream进行读写操作。

#include <fstream>
#include <iostream>

int main() {
    // 打开文件进行读取
    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;
    }

    return 0;
}

读取文件

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

写入文件

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

关闭文件

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

检查文件是否到达末尾

if (inputFile.eof()) {
    std::cout << "Reached end of file!" << std::endl;
}

追加内容到文件

在打开文件时使用std::ios::app标志:

std::ofstream appendFile("example.txt", std::ios::app);
appendFile << "Appended text" << std::endl;

删除文件

在C++中,你可以使用std::remove函数来删除文件:

#include <cstdlib>

int result = std::remove("example.txt");
if (result != 0) {
    std::cerr << "Error deleting file!" << std::endl;
}

重命名文件

使用std::rename函数来重命名文件:

int result = std::rename("oldname.txt", "newname.txt");
if (result != 0) {
    std::cerr << "Error renaming file!" << std::endl;
}

获取文件大小

使用std::filesystem库(C++17及以上)来获取文件大小:

#include <filesystem>

std::filesystem::path filePath("example.txt");
if (std::filesystem::exists(filePath)) {
    auto fileSize = std::filesystem::file_size(filePath);
    std::cout << "File size: " << fileSize << " bytes" << std::endl;
}

检查文件是否存在

if (std::filesystem::exists("example.txt")) {
    std::cout << "File exists!" << std::endl;
}

请注意,<filesystem>库是在C++17中引入的,如果你的编译器不支持C++17,你可能需要使用其他方法来检查文件是否存在或获取文件大小。

在使用这些技巧时,请确保你的程序有足够的权限来执行文件操作,并且在操作完成后关闭文件以释放资源。

0
看了该问题的人还看了