阅读量:141
C++中的文件操作函数主要包括以下几个:
- std::ifstream:用于从文件中读取数据。
使用方法示例:
#include
#include
int main() {
std::ifstream file("example.txt");
if (file.is_open()) {
std::string line;
while (std::getline(file, line)) {
std::cout << line class="hljs-built_in">close();
} else {
std::cout << "Unable to open file" << std class="hljs-keyword">return 0;
}
- std::ofstream:用于向文件中写入数据。
使用方法示例:
#include
#include
int main() {
std::ofstream file("example.txt");
if (file.is_open()) {
file << "Hello, World!" << std class="hljs-built_in">close();
} else {
std::cout << "Unable to open file" << std class="hljs-keyword">return 0;
}
- std::fstream:用于既能读取又能写入文件。
使用方法示例:
#include
#include
int main() {
std::fstream file("example.txt");
if (file.is_open()) {
std::string line;
while (std::getline(file, line)) {
std::cout << line class="hljs-built_in">clear(); // 清除错误标志
file.seekg(0, std::ios::end); // 定位到文件末尾
file << "Hello, World!" << std class="hljs-built_in">close();
} else {
std::cout << "Unable to open file" << std class="hljs-keyword">return 0;
}
- std::remove:用于删除文件。
使用方法示例:
#include
int main() {
if (std::remove("example.txt") != 0) {
std::cout << "Unable to delete file" << std class="hljs-keyword">return 0;
}
以上是一些常用的文件操作函数的简单示例,更详细的使用方法可以参考相关文档或教程。