文件的操作

文件的关联

文件操作首先需要包含头文件 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();             //输出完毕 关闭文件

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值