一、文件分类:
1.文本文件:文件使用文本的ASCII码形式存储在计算机中;
2.二进制文件:文件以文本的二进制形式存储在计算机中,用户一般不能直接读懂。
二、操作文件的三大类:
1、fstream:读写操作
2、ofstream:写操作
3、ifstream:读操作
三、常见文件打开方式:
ios::in 为读文件而打开文件
ios::out 为写文件而打开文件
ios::ate 打开后,初始位置在文件尾
ios::app 追加的方式写文件
ios::trunc 若文件存在,则先删除再创建,用于清空文件
ios::binary 二进制方式
注:文件打开方式可以配合使用,用 | 操作符
四、文本文件:
(一)、写文件:
#include<iostream>
#include<fstream> //第一步:包含文件操作的头文件
using namespace std;
void test01(){
//第二步:创建一个写入文件的对流象
ofstream ofs;
//第三步:打开文件,第一个参数为文件路径,第二个参数为打开方式
//如果文件不存在,则写文件时会先创建文件,再写入信息
ofs.open("D:\\C++\\传智cpp\\devcpp\\文件\\测试文件\\mytest.txt",ios::out);
//第四步:写入信息到文件中,把信息输出到文件
ofs << "姓名:张良" << endl;
ofs << "性别:男" << endl;
ofs << "年龄:18" << endl;
//第五步:关闭文件
ofs.close();
}
int main(){
test01();
system("pause");
return 0;
}
(二)、读文件:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void test01(){
//第二步:创建文件读取流对象
ifstream ifs;
//第三步:打开文件
ifs.open("D:\\C++\\传智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;
}
五、二进制文件
(一)、写入
#include<iostream>
#include<fstream>
using namespace std;
struct Person{
char m_Name[64];
int m_Age;
};
void test01(){
ofstream ofs;
ofs.open("D:\\C++\\传智cpp\\devcpp\\文件\\测试文件\\mytest_binary.txt",ios::out | ios::binary);
Person p = {"曹操",23};
//写入数据到文件里
ofs.write((const char*)&p, sizeof(Person));
ofs.close();
}
int main(){
test01();
system("pause");
return 0;
}
(二)、读取数据
#include<iostream>
#include<fstream>
using namespace std;
struct Person{
char m_Name[64];
int m_Age;
};
void test01(){
ifstream ifs;
ifs.open("D:\\C++\\传智cpp\\devcpp\\文件\\测试文件\\mytest_binary.txt",ios::in | ios::binary);
if(!ifs.is_open()){
cout << "文件打开失败" << endl;
return;
}
Person p;
ifs.read((char*) &p,sizeof(Person));
cout << "姓名:" << p.m_Name << ", 年龄:" << p.m_Age << endl;
ifs.close();
}
int main(){
test01();
system("pause");
return 0;
}
结语:对于文件操作,需要多查看函数手册,上网搜函数的使用。