文件操作步骤:

1, 包含头文件#include

2, 创建流对象:ofstream ofs

3, 打开文件:ofs.open("文件路径", 打开方式)

4, 写数据:ofs << "写入数据"

5, 关闭文件:ofs.close()

        打开方式:ios::in 读文件打开, ios:out,写文件打开, ios::ate, 打开文件, 定位到尾部

ios::trunc, 如果文件存在先删除, 在创建, ios::binary, 二进制文件

1, 写文件

#include

#include

#include

#include

#include

#include

#include

using namespace std;

void test()

{

ofstream aaa;

aaa.open("test.txt", ios::out);

aaa << "张三, 28";

aaa.close();

}

int main()

{

test();

system("pause");

return 0;

}

2, 读文件

ifstream aaa;

aaa.open("test.txt", ios::in);

//第一种方式

/*char buf [1024] = { 0 };

while (aaa >> buf)

{

cout << buf;

}*/

//第二种方式

/*char buf[1024] = { 0 };

while (aaa.getline(buf, sizeof(buf)))

{

cout << buf;

}*/

//第三种方式

/*string buf;

while (getline(aaa, buf))

{

cout << buf;

}*/

//第四种方式

char c;

while ((c = aaa.get()) != EOF)

{

cout << c;

}

3, 二进制文件

3-1, 写文件

class Person

{

public:

char m_name[64];

int m_age;

};

void test()

{

Person p = { "张三", 18 };

ofstream aaa("test1.txt", ios::out | ios::binary);

//aaa.open("test1.txt", ios::out | ios::binary);

aaa.write((const char*)&p, sizeof(Person));

aaa.close();

}

3-2, 读文件

class Person

{

public:

char m_name[64];

int m_age;

};

void test()

{

Person p;

ifstream aaa("test1.txt", ios::out | ios::binary);

//aaa.open("test1.txt", ios::out | ios::binary);

aaa.read((char*)&p, sizeof(Person));

cout << p.m_name << endl;

cout << p.m_age << endl;

aaa.close();

}

推荐文章

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: 


大家都在找:

c++:c++代码大全

学习:学习贯彻新时代中国特色社会主义思想主题教育

开发语言:开发语言是什么意思

大家都在看: