新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

C++文件函数有哪几种及如何使用,c++文件操作函数

发布时间:2023-08-18 07:59:32

C++文件函数有哪几种及如何使用

C++中的文件操作函数主要包括以下几个:
1. std::ifstream:用于从文件中读取数据。
使用方法示例:
```cpp
#include
#include
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;
}
```
2. std::ofstream:用于向文件中写入数据。
使用方法示例:
```cpp
#include
#include
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;
}
```
3. std::fstream:用于既能读取又能写入文件。
使用方法示例:
```cpp
#include
#include
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;
}
```
4. std::remove:用于删除文件。
使用方法示例:
```cpp
#include
int main() {
if (std::remove("example.txt") != 0) {
std::cout << "Unable to delete file" << std::endl;
}
return 0;
}
```
以上是一些经常使用的文件操作函数的简单示例,更详细的使用方法可以参考相关文档或教程。