以下是使用C++的类功能封装的文件操作类的示例代码:

#include <iostream>
#include <fstream>
#include <string>

class File {
private:
    std::string filename;

public:
    File(const std::string& fname) : filename(fname) {}

    bool exists() {
        std::ifstream file(filename);
        return file.good();
    }

    bool create() {
        std::ofstream file(filename);
        return file.is_open();
    }

    bool remove() {
        if (exists()) {
            return std::remove(filename.c_str()) == 0;
        }
        return false;
    }

    std::string read() {
        std::ifstream file(filename);
        std::string content;

        if (file.is_open()) {
            std::string line;
            while (std::getline(file, line)) {
                content += line + "\n";
            }
            file.close();
        }

        return content;
    }

    bool write(const std::string& content) {
        std::ofstream file(filename);
        if (file.is_open()) {
            file << content;
            file.close();
            return true;
        }
        return false;
    }
};

int main() {
    File file("example.txt");

    if (file.create()) {
        std::cout << "File created successfully!" << std::endl;
    } else {
        std::cout << "File creation failed!" << std::endl;
    }

    if (file.exists()) {
        std::cout << "File exists!" << std::endl;
    } else {
        std::cout << "File does not exist!" << std::endl;
    }

    std::string content = "Hello, world!";
    if (file.write(content)) {
        std::cout << "Content written to file successfully!" << std::endl;
    } else {
        std::cout << "Failed to write content to file!" << std::endl;
    }

    std::cout << "File content: " << file.read() << std::endl;

    if (file.remove()) {
        std::cout << "File removed successfully!" << std::endl;
    } else {
        std::cout << "Failed to remove file!" << std::endl;
    }

    return 0;
}

虽然这个示例使用了C++的类功能进行文件操作,但是其他实现(如文件打开、写入、删除等)都是使用C语言的标准库函数来完成的

使用c++的类功能封装一个文件操作类其他实现全部用c语言

原文地址: https://www.cveoy.top/t/topic/iMx3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录