温馨提示×

C++文件函数有哪些及怎么使用

c++
小亿
93
2023-08-17 23:15:01
栏目: 编程语言

C++中的文件操作函数主要包括以下几个:

  1. std::ifstream:用于从文件中读取数据。

使用方法示例:

#include <fstream>
#include <iostream>
int main() {
std::ifstream file("example.txt");
if (file.is_open()) {
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
file.close();
} else {
std::cout << "Unable to open file" << std::endl;
}
return 0;
}
  1. std::ofstream:用于向文件中写入数据。

使用方法示例:

#include <fstream>
#include <iostream>
int main() {
std::ofstream file("example.txt");
if (file.is_open()) {
file << "Hello, World!" << std::endl;
file.close();
} else {
std::cout << "Unable to open file" << std::endl;
}
return 0;
}
  1. std::fstream:用于既能读取又能写入文件。

使用方法示例:

#include <fstream>
#include <iostream>
int main() {
std::fstream file("example.txt");
if (file.is_open()) {
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
file.clear();  // 清除错误标志
file.seekg(0, std::ios::end);  // 定位到文件末尾
file << "Hello, World!" << std::endl;
file.close();
} else {
std::cout << "Unable to open file" << std::endl;
}
return 0;
}
  1. std::remove:用于删除文件。

使用方法示例:

#include <iostream>
int main() {
if (std::remove("example.txt") != 0) {
std::cout << "Unable to delete file" << std::endl;
}
return 0;
}

以上是一些常用的文件操作函数的简单示例,更详细的使用方法可以参考相关文档或教程。

0