文件的分类:
1.文本类文件:文件使用文本的ASCII码形式存储在计算机中。
2.二进制文件:文件以文本的二进制形式存储在计算机中。
文件操作的头文件
#include<fstream>
对文件的基本操作
fstream //文件的读与写
ofstream //文件的写操作
ifstream //文件的读操作
文件的几种打开方式
ios::in //为读文件而打开文件
ios::out //为写文件而打开文件
ios::ate //打开后,光标初始位置在文件末尾
ios::app //以追加的方式写文件
ios::trunc //如果文件存在,则先删除原文件再创建,用于清空文件
ios::binary //二进制方式打开文件
文件指针的用法
ios::beg //文件头
ios::end //文件尾
ios::cur //当前位置
文件指针应用举例
file.seekg(0,ios::beg); //让文件指针定位到文件开头
file.seekg(0,ios::end); //让文件指针定位到文件末尾
file.seekg(n,ios::cur); //让文件指针从当前位置向后移动n个字节
file.seekg(-n,ios::cur); //让文件指针从当前位置向前移动1n个字节
file.seekg(n,ios::beg); //让文件指针定位到离文件开头n个字节的位置
写文件
#include<iostream>
#include<fstream> //包含文件操作的头文件
using namespace std;
void test1()
{
//创建一个写入文件的对象
ofstream ofs;
//打开文件,第一个参数为文件路径,第二个参数为打开方式
//如果不声明文件路径,其默认路径在源代码文件夹处
//如果文件不存在,则写文件时会先创建文件,再写入信息
ofs.open("F:\\C++\\byh.cpp\\devcpp\\mytest.txt",ios::out);
//写入信息到文件中,把信息输出到文件
ofs << "姓名:张三" << endl;
ofs << "性别:男" << endl;
ofs << "年龄:97" << endl;
//关闭文件
ofs.close();
}
int main()
{
test1();
system("pause");
return 0;
}
读文件
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void test01(){
//创建文件读取流对象
ifstream ifs;
//打开文件
ifs.open("F:\\C++\\byh.cpp\\devcpp\\mytest.txt",ios::in);
if(!ifs.is_open())//判断文件是否打开
{
cout << "文件打开失败" << endl;
return;
}
//读取数据
//方法一:一组词一组词的读,用空格分割组
char buf2[1024] = {0};
while(ifs >> buf2)
{
cout << buf2 << endl;
}
cout << "--------------------------------" <<endl;//输出分割线
//将文件读取流指针移到文件开头
ifs.clear(ios::goodbit);
ifs.seekg(ios::beg);
//方法二:一行一行的读
string buf1;
while(getline(ifs,buf1))//读到文件末尾结束
{
cout << buf1 << endl;
}
cout << "---------------------------" << endl;
ifs.clear();
ifs.seekg(ios::beg);
//方法三:也是一行一行的读
char buf3[1024] = {0};
while(ifs.getline(buf3,sizeof(buf3)))
{
cout << buf3 << endl;
}
cout << "--------------------------------" <<endl;
//方法四:一个字符一个字符的读
ifs.clear();
ifs.seekg(0,ios::beg);
char ch;
while( (ch=ifs.get()) != EOF)
{
cout << ch;
}
//第五步:关闭文件
ifs.close();
int main()
{
test01();
system("pause");
return 0;
}
本人才疏学浅,如有不足,请多指教。