c++文件操作功能大全以及代码示例
时间: 2024-05-10 08:19:03 浏览: 10
C++中的文件操作可以分为以下几个方面:
1. 文件创建和打开
2. 文件读取和写入
3. 文件关闭和删除
下面是一些文件操作的代码示例:
1. 文件创建和打开
```c++
#include <fstream>
using namespace std;
int main() {
// 创建文件
ofstream outfile("test.txt");
// 打开文件
ifstream infile("test.txt");
return 0;
}
```
2. 文件读取和写入
```c++
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream outfile("test.txt");
outfile << "Hello, world!" << endl;
outfile.close();
ifstream infile("test.txt");
string str;
getline(infile, str);
cout << str << endl;
infile.close();
return 0;
}
```
3. 文件关闭和删除
```c++
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream outfile("test.txt");
outfile << "Hello, world!" << endl;
outfile.close();
remove("test.txt");
return 0;
}
```
这些只是文件操作的基础知识,还有很多高级操作,比如二进制文件读写、文件指针操作等。需要根据具体需求来学习。