文件代表存储数据或信息的介质,流是指字节序列。在文件中,我们使用文本或二进制数据来永久存储数据,并通过读写字节的形式对文件进行读取或写入,所以我们使用术语文件流,在C++中,我们使用头文件<fstream>
,来使用文件流。
文件流中的操作:
open()
read()
write()
close()
我们通过指定文件的路径和操作模式来创建或者打开文件,操作可以是读、写、追加和截断,语法:文件流对象.open("路径",ios::mode);
st.open("E:\yetaozi.txt",ios::out);
st.open("E:\yetaozi.txt",ios::in);
st.open("E:\yetaozi.txt",ios::app);
st.open("E:\yetaozi.txt",ios::trunc);
#include<iostream>
#include<conio>
#include <fstream>
using namespace std;
int main()
{
fstream st; // 第一步:创建文件流对象
st.open("E:\yetaozi.txt",ios::out); // 第二步:新建文件文件
if(!st) // 第三步:检查文件是否创建成功
{
cout<<"文件创建失败";
}
else
{
cout<<"新文件创建成功";
st.close(); // 第四步:关闭文件
}
getch();
return 0;
}
#include <iostream>
#include<conio>
#include <fstream>
using namespace std;
int main()
{
fstream st; // 第一步:创建文件流对象
st.open("E:\yetaozi.txt",ios::out); // 第二步:新建文件文件
if(!st) // 第三步:检查文件是否创建成功
{
cout<<"文件创建失败";
}
else
{
cout<<"文件创建成功";
st<<"Hello"; // 第四步:写入内容
st.close(); // 第五步:关闭文件
}
getch();
return 0;
}
在这里,我们将内容写入到文件,因此,我们使用 ios::out。示例中,在 "st <<" 之后的内容会被写入到文件中。
#include <iostream>
#include<conio>
#include <fstream>
using namespace std;
int main()
{
fstream st; // 第一步:创建文件流对象
st.open("E:\yetaozi.txt",ios::in); // 第二步:新建文件文件
if(!st) // 第三步:检查文件是否创建成功
{
cout<<"No such file";
}
else
{
char ch;
while (!st.eof())
{
st >>ch; // 第四步:从文件读取内容
cout << ch; // 打印内容
}
st.close(); // 第五步:关闭文件
}
getch();
return 0;
}
我们使用 ios::in读取文件中的内容,通过“st >>”把文件的内容被读取到变量ch中。
它由 文件流对象.close()
完成。
#include <iostream>
#include<conio>
#include <fstream>
using namespace std;
int main()
{
fstream st; // 第一步:创建文件流对象
st.open("E:\yetaozi.txt",ios::out); // 第二步:新建文件文件
st.close(); // 第四步:关闭文件
getch();
return 0;
}
文件流有几个常用的函数,如:
tellp()
- 获得put(写入)指针位置。tellg()
- 获得get(获取)指针的位置。seekp()
- 对put指针定位,有两个参数,第一个参数是偏移量,可以有正负值,正数代表向前偏移,负数代表向后偏移;第二个参数是基地址,可以是ios::cur、ios::beg和ios::end,分别表示当前位置、开始位置和结束位置。seekg()
- 对get指针定位,用法如seekp。put()
- 将单个字符写入文件。get()
- 从文件中读取单个字符。请看下面的例子:
#include <iostream>
#include<conio>
#include <fstream>
using namespace std;
int main()
{
fstream st; // 创建文件流对象
st.open("E:\yetaozi.txt",ios::out); // 创建新文件
if(!st) // 检查是否创建成功
{
cout<<"文件创建失败";
}
else
{
cout<<"文件创建成功"<<endl;
st<<"Hello Friends"; //将字符串写入文件
// 获取文件指针的位置
cout<<"put指针的位置是:"<<st.tellp()<<endl;
st.seekp(-1, ios::cur); //当前put指针位置后移一位
// 再来查看当前文件指针文件
cout<<"put指针的位置是:"<<st.tellp()<<endl;
st.close(); // 关闭文件
}
st.open("E:\yetaozi.txt",ios::in); // 以只读模式打开文件
if(!st) //检查文件是否存在
{
cout<<"文件不存在";
}
else
{
char ch;
st.seekg(5, ios::beg); // 从起始位置偏移5.
cout<<"get指针的位置是:"<<st.tellg()<<endl; // 获取get指针位置
cout<<endl;
st.seekg(1, ios::cur); // 当前get指针位置向后移一位
cout<<"get指针的位置是: "<<st.tellg()<<endl; // 获取get指针位置
st.close(); //关闭文件
}
getch();
return 0;
}
以上实例输出结果:
文件创建成功 put指针的位置是: 13 put指针的位置是: 12 get指针的位置是: 5 get指针的位置是: 6