最近在回顾C++的知识,所以整理了这些博客
1、文件和流
cin对象(标准输入流对象)允许程序从键盘或者其他设备输入数据,cout对象(标准输出流对象)允许将程序数据输出到屏幕或者其他设备。C++中,必须包含头文件< iostream>和< fstream>;
2、创建顺序文件
首先贴一段代码:
// Create a sequential file.
#include <iostream>
#include <string>
#include <fstream> // file stream
#include <cstdlib> // exit function prototype
using namespace std;
int main()
{
ofstream outClientFile( "clients.dat", ios::out );
if ( !outClientFile ) // overloaded ! operator
{
cerr << "File could not be opened" << endl;
exit( 1 );
} // end if
cout << "Enter the account, name, and balance." << endl
<< "Enter end-of-file to end input.\n? ";
int account;
string name;
double balance;
// 读数据,然后存入文件
while ( cin >> account >> name >> balance )
{
outClientFile << account << ' ' << name << ' ' << balance << endl;
cout << "? ";
} // end while
} // end main
从项目文件中可以看到多出了一个文件”clients.dat”;用记事本打开会显示从命令行录入的内容;
主要通过创建ifstream,ofstream,以及fstream的对象来打开文件。
上述代码主要用于输出(从命令行传向文件),所以创建了一个ofstream对象。有两个参数——文件名和文件打开模式——传递到对象的构造函数中。
对于ofstream对象,文件打开模式可以是:
ios::out ——向一个文件输出数据;(如果原文件有数据,将会被清空,如果原文件不存在,则会先创建一个空的文件)
ios::app ——讲数据输出到文件的结尾,不改变在文件中原有的数据;
ofstream文件还可以这样创建:
ofstream outClientFile;
outClientFile.open("clients.dat",ios::out);
相当于:
ofstream outClientFile("clients.dat");
outClientFile << account << ' ' << name << ' ' << balance << endl;
通过流插入运算符<<和对象outClientFile,向文件中写入一组数据;
3、从顺序文件读取数据
#include <iostream>
#include <fstream> // file stream
#include <iomanip>
#include <string>
#include <cstdlib> // exit function prototype