#includeofstream ofsofs.open("文件路径", 打开方式)ofs << "写入的数据"ofs.close()| 打开方式 | 解释 |
|---|---|
| ios::in | 为读文件而打开文件 |
| ios::out | 为写文件而打开文件 |
| ios::ate | 初始位置:文件尾 |
| ios::app | 追加方式写文件 |
| ios::trunc | 如果文件存在先删除,再创建 |
| ios::binary | 二进制方式 |
如果需要几种配合使用,使用|操作符
例如:ios::binary | ios::out
void o_op()
{
ofstream ofs;
string f_url = "/Users/###/Desktop/123.txt";
ofs.open(f_url,ios::out);
ofs << "姓名: 张三" << endl;
ofs << "年龄:18" << endl;
ofs.close();
cout << "end" << endl;
}
读文件与写文件步骤相似,但是读取方式相对比较多
#includeifstream ifsifs.open("文件路径", 打开方式)ifs.close()void i_op()
{
ifstream ifs;
string f_url = "/Users/###/Desktop/123.txt";
ifs.open(f_url,ios::in);
if (!ifs.is_open())
{
cout << "文件打开失败" << endl;
return;
}
// 第一种:
char buf[1024] = {0};
while (ifs >> buf)
{
cout << buf << endl;
}
// 第二种:
// char buf[1024] = {0};
// while (ifs.getline(buf, sizeof(buf))) {
// cout << buf << endl;
// }
// 第三种:
// string buf;
// while (getline(ifs, buf))
// {
// cout << buf << endl;
// }
// 第四种:一个一个读,效率比较低; EOF -> end of file
// char c;
// while ((c = ifs.get()) != EOF)
// {
// cout << c;
// }
//
// ifs.close();
cout << "end" << endl;
}
二进制方式写文件主要利用流对象调用成员函数write
函数原型:ostream& write(const char * buffer, int len)
参数解释:字符指针buffer指向内存中一段存储空间,len是读写的字节数
class Person
{
public:
char m_Name[64]; // 姓名
int m_Age; // 年龄
};
void testWrite()
{
ofstream ofs;
string f_url = "/Users/runhe_ios_jh/Desktop/1234.txt";
ofs.open(f_url, ios::out | ios::binary);
Person p = {"李四", 10};
ofs.write((const char *)&p, sizeof(Person));
ofs.close();
}
二进制方式读文件主要利用流对象调用成员函数read
函数原型:istream& read(char * buffer, int len)
参数解释:字符指针buffer指向内存中一段存储空间,len是读写的字节数
void testRead()
{
ifstream ifs;
string f_url = "/Users/runhe_ios_jh/Desktop/1234.txt";
ifs.open(f_url, 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();
}