需要用到一个头文件<fstream>;
(该代码来源于《数据结构》(第二版)殷人坤)
要创建一个输入(输出)流,必须声明它为ifstream(ofstream)类的实例。
执行输入输出操作的流必须声明它为fstream类的实例。
#include <stdlib.h>
#include <stdio.h>
#include <fstream> //fstream和fstream.h的不同可类比iostream和iostream.h的不同
#include <iostream> //iostream和iostream.h的不同在上一篇文章中
using namespace std; //命名空间
int main() //必须是int型!
{
ifstream inFile;
ofstream outFile;
outFile.open("my.bat",ios::out); //ios::out,表明该文件用于输出,可缺省。
char univ[] = "Tsinghua",name[10];
int course = 2431,number;
outFile << univ << endl;
outFile << course << endl;
inFile.open("my.bat",ios::in); //ios::in,表明该文件用于输入,可缺省。
if(!inFile){
cerr << "无法打开my.bat"<<endl;
exit(1);
}
char c,d;
inFile >> name >> c >> d >> number; //这里把my.bat中的数据赋值给了name,c,d。但是,空格和回车不识别。
cout << name << endl;
cout << c << endl;
cout << d << endl;
cout << number << endl;
outFile << "name:"<<name << endl;
outFile << "number:"<< number <<endl;
system("pause");
return 0;
}
结果为:
my.bat中显示如下
Tsinghua
2431
name:Tsinghua
number:31
编译器中显示如下:
Tsinghua
2
4
31