概述:此C++示例详解文件操作:创建、删除、判断存在、写入、读取和修改文件内容。清晰演示了常见文件处理方法及源代码实现。

以下是一个简单的C++实例,演示如何进行文件操作,包括创建文件、删除文件、判断文件是否存在、向文件写入内容、读取文件内容以及修改文件内容。

#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdio>

// 创建文件
void createFile(const std::string& filename) {
    std::ofstream file(filename);
    if (file.is_open()) {
        std::cout << "文件创建成功: " << filename << std::endl;
        file.close();
    } else {
        std::cerr << "无法创建文件: " << filename << std::endl;
    }
}

// 删除文件
void deleteFile(const std::string& filename) {
    if (std::remove(filename.c_str()) == 0) {
        std::cout << "文件删除成功: " << filename << std::endl;
    } else {
        std::cerr << "无法删除文件: " << filename << std::endl;
    }
}

// 判断文件是否存在
bool fileExists(const std::string& filename) {
    std::ifstream file(filename);
    return file.good();
}

// 向文件写入内容
void writeFile(const std::string& filename, const std::string& content) {
    std::ofstream file(filename);
    if (file.is_open()) {
        file << content;
        std::cout << "内容成功写入文件: " << filename << std::endl;
        file.close();
    } else {
        std::cerr << "无法打开文件进行写入: " << filename << std::endl;
    }
}

// 读取文件内容
std::string readFile(const std::string& filename) {
    std::ifstream file(filename);
    std::stringstream buffer;
    if (file.is_open()) {
        buffer << file.rdbuf();
        file.close();
    } else {
        std::cerr << "无法打开文件进行读取: " << filename << std::endl;
    }
    return buffer.str();
}

// 修改文件内容
void modifyFile(const std::string& filename, const std::string& newContent) {
    std::string content = readFile(filename);
    writeFile(filename, content + "\n" + newContent);
}

int main() {
    const std::string filename = "example.txt";
    
    // 创建文件
    createFile(filename);

    // 写入内容
    writeFile(filename, "Hello, File!");

    // 读取并输出内容
    std::cout << "文件内容: " << readFile(filename) << std::endl;

    // 修改文件内容
    modifyFile(filename, "Appended Text");

    // 读取并输出修改后的内容
    std::cout << "修改后的文件内容: " << readFile(filename) << std::endl;

    // 删除文件
    deleteFile(filename);

    return 0;
}

在这个例子中,我们使用了 <iostream> 和 <fstream> 头文件来进行文件操作。通过各个函数,实现了创建文件、删除文件、判断文件是否存在、向文件写入内容、读取文件内容以及修改文件内容的功能。在 main 函数中,我们演示了如何使用这些函数来操作文件。