C++ 文件操作类封装示例:简化文件读写操作

以下是一个简单的 C++ 文件操作类的封装示例,方便开发者快速实现文件读写操作:

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

class File {
private:
    std::string filename;
    std::ifstream infile;
    std::ofstream outfile;
    
public:
    File(const std::string& filename) : filename(filename) {}
    
    void openInputFile() {
        infile.open(filename);
        if (!infile) {
            std::cerr << 'Failed to open input file: ' << filename << std::endl;
        }
    }
    
    void openOutputFile() {
        outfile.open(filename);
        if (!outfile) {
            std::cerr << 'Failed to open output file: ' << filename << std::endl;
        }
    }
    
    void closeInputFile() {
        infile.close();
    }
    
    void closeOutputFile() {
        outfile.close();
    }
    
    std::string readLine() {
        std::string line;
        std::getline(infile, line);
        return line;
    }
    
    void writeLine(const std::string& line) {
        outfile << line << std::endl;
    }
};

int main() {
    File file('example.txt');
    
    file.openInputFile();
    std::string line = file.readLine();
    std::cout << 'Read line: ' << line << std::endl;
    file.closeInputFile();
    
    file.openOutputFile();
    file.writeLine('This is a test');
    file.closeOutputFile();
    
    return 0;
}

上述代码中,File 类封装了文件操作的一些基本功能,包括打开输入文件、打开输出文件、关闭输入文件、关闭输出文件、读取文件中的一行以及写入一行到文件中。在 main 函数中,我们可以使用 File 类来进行文件操作,例如打开一个文件、读取一行、关闭文件、写入一行等操作。

请注意,上述代码只是一个简单的示例,仅供参考。在实际使用中,你可能需要添加更多的错误处理逻辑、异常处理等。

C++ 文件操作类封装示例:简化文件读写操作

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

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