文本文件
c++中文件操作需要包含<fsream>
-
操作文件的三大类
ofstream; 写 ifstream; 读 fsteam; 读写
写文件
- 包含头文件
- 创建流对象
- 打开文件
- 写数据
- 关闭文件
#include <fstream>
void test01()
{
ofstream ofs;
ofs.open("test.txt", ios::out);
ofs << "write some to test.txt" << endl;
ofs.close();
}
int main()
{
test01();
return 0;
}
读文件
- 包含读文件
- 创建流对象
- 打开文件并判读是否打开成功
- 读数据
- 关闭文件
#include <fstream>
void test01()
{
ifstream ifs;
ifs.open("test.txt", ios::in);
if (!ifs.is_open())
{
cout << "open file failed!" << 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;
}
//char c;
//while ((c = ifs.get()) != EOF)
//{
// cout << c;
//}
}
int main()
{
test01();
return 0;
}
二进制文件
打开方式指定为 ios::binary
二进制写
#include <fstream>
class Person
{
public:
char m_Name[64];
int m_Age;
};
void test01()
{
ofstream ofs;
ofs.open("person.txt", ios::out | ios::binary);
Person p = { "Tome", 18 };
ofs.write((const char *) &p, sizeof (Person));
ofs.close();
}
int main()
{
test01();
return 0;
}
二进制读
#include <fstream>
class Person
{
public:
char m_Name[64];
int m_Age;
};
void test01()
{
ifstream ifs("person.txt", ios::in | ios::binary);
if (!ifs.is_open())
{
cout << "file open failed!" << endl;
}
Person p;
ifs.read((char*)&p, sizeof(Person));
cout << p.m_Name << ":" << p.m_Age << endl;
//cout << sizeof(Person) << endl;
ifs.close();
}
int main()
{
test01();
return 0;
}