文件操作
文件操作是读入和写出,文件类型有文本文件和二进制文件。在读文件操作中,可以使用C语言的char或者C++的string。方式:
1)ifs>>str;
2)全局函数getline();
3)成员函数ifs.getline();
4)成员函数write和read搭配使用。
举例
#include<iostream>
using namespace std;
#include<fstream>
#include<string>
class Person
{
public:
char m_name[64];
int m_age;
};
void test08()
{
//文本文件的写入
fstream fs;
fs.open("文本文件1.txt", ios::out);
fs << "皮皮" << endl;
fs.close();
//文本文件的读取
fs.open("文本文件.txt", ios::in);
if (!fs.is_open())
{
cout << "打开文件失败" << endl;
return;
}
//打开方式1
//string str;
//while (fs>>str)
//{
// cout << str << endl;
//}
//while (getline(fs, str))
//{
// cout << str << endl;
//}
//打开方式2
char c[1024] = { 0 };
while (fs >> c)
{
cout << c << endl;
}
while (fs.getline(c, sizeof(c)))
{
cout << c << endl;
}
fs.close();
}
void test09()
{
//文本文件的写入
Person p1 = { "张三",18 };
fstream fs;
fs.open("文本文件2.txt", ios::out);
fs.write((const char*)&p1, sizeof(p1));
fs.close();
//文本文件的读取
fs.open("文本文件2.txt", ios::in);
if (!fs.is_open())
{
cout << "打开文件失败" << endl;
return;
}
//打开方式3
Person p;
fs.read((char*)&p, sizeof(p));
cout << p.m_name << " " << p.m_age << endl;
fs.close();
}
int main()
{
//test08();
test09();
system("pause");
return 0;
}