文件的关联
文件操作首先需要包含头文件 fstream。
fstream头文件中定义用于输入的ifstream类和用于输出的ofstream类。
可以通过使用这两个类来声明对象:
ifstream in_file;
ofstream out_file;
将我们声明的对象与文件关联起来:
out_file.open(“name.txt”);
in_file.open(“name.txt”);
Ps:打开的文件最后一定要关闭。例如:out_file.close();
下面的例子包含了向文件输入字符串和从文件读取字符串:
#include
#include
#include
using namespace std;
main()
{
char filename[20]; //定义文件名字符数组
ofstream out_file;
cout << "Enter file name: "; //输入文件名
cin >>filename;
out_file.open(filename); //使ouffile关联文件
cout << "Please enter string(q to quit): "<<endl;
char str[100];
cin.getline(str,100).get(); //输入文件名 并吸收最后的回车符
while(strcmp(str,"q")!=0) //输入想要输进文件中的字符串 单独输入 q 退出输入。
{
out_file << str << endl; // 像使用cout 一样输入到文件中
cin.getline(str,100);
}
out_file.close(); // 输入完毕 关闭文件
ifstream in_file;
in_file.open(filename);
string item;
getline(in_file,item); //从文件中获取以'\n'为结尾的字符串
while(in_file)
{
cout <<item <<endl; //输出获取的字符串
getline(in_file,item);
}
in_file.close(); //输出完毕 关闭文件
}