说明:程序运行时产生的文件,都属于临时文件,程序一旦结束就会被释放,通过文件可以将数据保存。
c++对文件的操作需要包含头文件
操作文件的三大类:
1、ofstream:写操作
2、ifstream:读操作
3、fstream:读写操作
文件类型主要分为两种:
1、文本文件–文件以ASCII码存储在计算机中
2、二进制文件–文件以文本的二进制形式存储在计算机中,用户一般不能直接读
1、文本文件
1、写文件
步骤:
1、包含头文件
#include
2、创建流对象
ofstream ofs;
3、打开文件
ofs.open(“文件路径”,打开方式);
4、写数据
ofs<<“写入的数据”;
5、关闭文件
ofs.close();
文件打开方式:
ios::in 为读文件而打开文件
ios::out 为写文件而打开文件
ios::ate 初始位置,文件末尾
ios::app 追加方式写文件
ios::trunc 如果文件已经存在,先删除,在创建
ios::binary 二进制
#include<iostream>
using namespace std;
#include<fstream>
int main()
{
/*C:\Users\admin\Desktop\c++基础\c++文件的读写*/
ofstream ofs;
ofs.open("C://Users//admin//Desktop//c++基础//c++文件的读写//test.txt", ios::out);
ofs << "姓名:张三" << endl;
ofs << "年龄:28" << endl;
ofs << "性别:男" << endl;
system("pause");
return 0;
}
2、读文件
读文件的步骤:
1、包含头文件
#include
2、创建流文件
ifstream ifs;
3、打开文件并看文件是否能够打开成功
ifs.open(“文件路径”,打开方式);
4、读数据
四种方式读取
5、关闭文件
ifs.close();
#include<iostream>
#include<fstream>
using namespace std;
void test()
{
/*C:\Users\admin\Desktop\c++基础\c++文件的读写*/
ifstream ifs;
ifs.open("C://Users//admin//Desktop//c++基础//c++文件的读写//test2.txt", ios::in);
//判断是否打开
if (!ifs.is_open())
{
cout << "文件打开失败!" << endl;
return;
}
//读数据
//1、
/*char buf[1024] = { 0 };
while (ifs >> buf)
{
cout << buf << endl;
}*/
//2、
/*char buf[1024] = { 0 };
while (ifs.getline(buf, sizeof(buf)))
{
cout << buf << endl;
}*/
//3、
/*string buf;
while (getline(ifs, buf))
{
cout<<buf<<endl;
}*/
//4、效率低,不建议使用
char c;
while ((c = ifs.get()) != EOF)
{
cout << c;
}
ifs.close();
}
int main()
{
test();
system("pause");
return 0;
}
2、二进制文件
1、写文件
二进制写文件主要利用流对象调用成员函数write
函数原型:ostream& write(const char*buffer,int len);
参数解释:字符指针buffer指向内存中的一段存储空间,len是读写的字节数
void Write()
{
ofstream ofs;
ofs.open("C://Users//admin//Desktop//c++基础//c++文件的读写//test3.txt",ios::out|ios::binary);
Person p = { "张三",28 };
ofs.write((const char*)&p, sizeof(Person));
ofs.close();
}
2、读文件
二进制读文件主要利用流对象调用成员函数read
函数原型:istream& read( char*buffer,int len);
参数解释:字符指针buffer指向内存中的一段存储空间,len是读写的字节数
void Read()
{
ifstream ifs;
ifs.open("C://Users//admin//Desktop//c++基础//c++文件的读写//test3.txt", ios::in | ios::binary);
if (!ifs.is_open())
{
cout << "文件打开失败" << endl;
return;
}
Person p;
ifs.read((char*)&p, sizeof(Person));
cout << "姓名:" << p.name << " 年龄:" << p.age << endl;
ifs.close();
}