C++ 文件操作类封装示例:使用 C 库函数
下面是一个封装了文件操作的 C++ 类的示例代码,使用了 C 库函数进行文件操作:
#include <iostream>
#include <cstdio>
class File {
public:
File(const std::string& filename, const std::string& mode)
{
file = std::fopen(filename.c_str(), mode.c_str());
if (file == nullptr) {
std::cerr << 'Failed to open file: ' << filename << std::endl;
}
}
~File()
{
if (file != nullptr) {
std::fclose(file);
}
}
bool isOpen() const
{
return file != nullptr;
}
std::string readLine() const
{
char buffer[256];
if (std::fgets(buffer, sizeof(buffer), file) != nullptr) {
return std::string(buffer);
}
return '';
}
void writeLine(const std::string& line)
{
std::fputs(line.c_str(), file);
}
private:
std::FILE* file;
};
int main()
{
File file('example.txt', 'w');
if (file.isOpen()) {
file.writeLine('Hello, World!');
}
File file2('example.txt', 'r');
if (file2.isOpen()) {
std::cout << file2.readLine();
}
return 0;
}
这个示例中,File 类封装了文件操作,包括打开文件、读取文件行和写入文件行等功能。它使用了 C 库函数fopen、fclose、fgets 和 fputs 进行文件操作。在 main 函数中,我们首先创建一个文件对象 file,打开文件并写入一行文本。然后我们再创建一个文件对象 file2,打开同一个文件并读取一行文本,然后将其输出到控制台。
原文地址: https://www.cveoy.top/t/topic/qsKY 著作权归作者所有。请勿转载和采集!