c++文件操作实验小结
时间: 2023-06-23 07:08:21 浏览: 44
在C++中,文件操作是非常常见的一种操作。通过文件操作,我们可以读取、写入文件,实现数据的持久化存储。下面是一些关于C++文件操作的实验小结:
1.文件读取:
文件读取可以使用ifstream类,它是从istream派生而来的一个类,可以用来读取文件中的内容。
```c++
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream infile("test.txt"); //打开文件
if(!infile.is_open()) //判断文件是否打开成功
{
cout<<"文件打开失败!"<<endl;
return 0;
}
char ch;
while(infile.get(ch)) //从文件中读取字符
{
cout<<ch;
}
infile.close(); //关闭文件
return 0;
}
```
2.文件写入:
文件写入可以使用ofstream类,它是从ostream派生而来的一个类,可以用来写入文件。
```c++
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outfile("test.txt"); //打开文件
if(!outfile.is_open()) //判断文件是否打开成功
{
cout<<"文件打开失败!"<<endl;
return 0;
}
outfile<<"Hello, world!"; //向文件中写入内容
outfile.close(); //关闭文件
return 0;
}
```
3.文件复制:
文件复制可以使用ifstream和ofstream类配合使用,先读取文件中的内容,再将其写入到另一个文件中。
```c++
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream infile("test.txt"); //打开源文件
if(!infile.is_open()) //判断源文件是否打开成功
{
cout<<"源文件打开失败!"<<endl;
return 0;
}
ofstream outfile("test_copy.txt"); //打开目标文件
if(!outfile.is_open()) //判断目标文件是否打开成功
{
cout<<"目标文件打开失败!"<<endl;
return 0;
}
char ch;
while(infile.get(ch)) //从源文件中读取内容并写入到目标文件中
{
outfile.put(ch);
}
infile.close(); //关闭源文件
outfile.close(); //关闭目标文件
return 0;
}
```
总之,文件操作是C++中常用的操作之一,需要掌握常用的文件操作函数和类,以便实现数据的持久化存储和读取。