C++ 类封装文件操作:C 语言实现文件 I/O
C++ 类封装文件操作:C 语言实现文件 I/O
本示例演示如何使用 C++ 类封装文件操作,并使用 C 语言标准库函数实现文件 I/O 操作。
#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++ 类来封装文件操作,但文件 I/O 操作的具体实现(如打开、写入、删除文件)仍然使用了 C 语言标准库函数。
代码解释:
-
File类:- 私有成员
filename用于存储文件名。 - 公有成员函数:
exists():检查文件是否存在。create():创建文件。remove():删除文件。read():读取文件内容。write():写入文件内容。
- 私有成员
-
main()函数:- 创建一个
File对象,并使用其方法进行文件操作,例如创建文件、写入内容、读取内容和删除文件。
- 创建一个
优点:
- 通过 C++ 类封装文件操作,使代码更易于维护和扩展。
- 可以使用 C 语言标准库函数实现文件 I/O 操作,保持代码效率。
注意:
- 为了简洁,示例代码中没有进行错误处理。在实际应用中,应添加必要的错误处理机制。
- 由于使用 C 语言标准库函数进行文件操作,代码的可移植性可能受限。
相关主题:
- C++ 文件操作
- C 语言文件 I/O
- 类封装
原文地址: https://www.cveoy.top/t/topic/qsK0 著作权归作者所有。请勿转载和采集!