文件读写

 1 //读出图书信息
 2 //将stdin与文件绑定
 3 freopen("./account/books.dat","r",stdin);
 4 //读入书本的数量
 5 int num = 0;
 6 cin >> num;
 7 //读书书本信息到容器中
 8 for(int i = 0;i < num;i++)
 9 {
10     Book tmp;
11     cin >> tmp.m_name;
12     cin >> tmp.m_author;
13     cin >> tmp.m_id;
14     cin >> tmp.m_loan_id;
15     cin >> tmp.m_engage_id;
16     cin >> tmp.m_type;
17     cin >> tmp.m_loan_times;
18     cin >> tmp.m_time;
19     books.push_back(tmp);
20 }
21     
22 fclose(stdin);
23 //将stdin与终端绑定
24 freopen("/dev/tty","r",stdin);

 

 1 //保存图书信息
 2 //将stdout与图书文件绑定
 3 freopen("./account/books.dat","w",stdout);
 4 //写入书本的数量
 5 cout << books.size() << endl;
 6 //写入书本的信息
 7 for(unsigned int i = 0;i < books.size();i++)
 8 {
 9     cout << books[i].m_name << endl;
10     cout << books[i].m_author << endl;
11     cout << books[i].m_id << endl;
12     cout << books[i].m_loan_id << endl;
13     cout << books[i].m_engage_id << endl;
14     cout << books[i].m_type << endl;
15     cout << books[i].m_loan_times << endl;
16     cout << books[i].m_time<< endl;
17 }
18 fclose(stdout);
19 //将stdout与终端文件绑定
20 freopen("/dev/tty","w",stdout);

 

posted @ 2018-08-25 14:48  Scott9527  阅读(139)  评论(0编辑  收藏  举报