文本文件操作

C++中文本文件操作主要是通过fstream头文件以及其中的ifstream对象以及ofstream对象

首先,我们在使用ifstream对象以及ofstream对象时必须将其与文件关联起来来实例化对象

比如这样实例化一个outFile对象,这个对象代表这你对文本文件要进行的一系列操作。

ofstream outFile;

其次,ifstream对象、ofstream对象与我们的cin对象和cout对象基本上用法一致,cout、cin的一些操作他们 也有。

写入文本文件:

#include <iostream>
using namespace std;
#include <fstream>

int main()
{
    ofstream outFile;
    ofstream fout;
    outFile.open("fish.txt");
    char filename[50];
    cin >> filename;
    fout.open(filename);

    double wt = 125.8;
    outFile << wt;
    char line[81] = "Objects are closer than they appear.";
    fout << line << endl;

    system("pause");
    return 0;
}

上面代码首先分别实例化outFile和fout对象代表接下来对两个文本文件进行操作,ouFile.open("fish.txt")打开fish.txt文件(如果没有会自己创建,如果存在会清空之前的数据!!!)

同样的我们从键盘读取filename并用fout open一下,接下来outFile<<wt表示将wt写入outFile对应的文件即fish.txt中!,fout也是同理。

可以看到outFile<<wt这种格式与cout很像!事实上ifstream对象、ofstream对象与我们的cout对象和cin对象基本上用法一致。

#include <iostream>
using namespace std;
#include <fstream>

int main()
{
    ofstream outFile;
    outFile.open("carinfo.txt");

    string automobile = "benz";

    outFile << fixed;
    outFile.precision(2);
    outFile.setf(ios_base::showpoint);
    outFile << "Make and model: " << automobile << endl;
    outFile.close();

    system("pause");
    return 0;
}

可以看到outFile与cout一样可以outFile<<fixed设置用一般的方式输出浮点数而不是科学计数法,并且还可以outFile.percision设置精度等等,总之将ofstream类比于cout是可以的!

我们还可以在.open后面加上文件打开方式:

 比如:

#include <fstream>

void test01()
{
    ofstream ofs;
    ofs.open("test.txt", ios::out);

    ofs << "姓名:张三" << endl;
    ofs << "性别:男" << endl;
    ofs << "年龄:18" << endl;

    ofs.close();
}

int main() {

    test01();

    system("pause");

    return 0;
}

读取文本文件

读取文本文件时.open里的文件必须是已存在的,不会像写入文本文件一样给你创建。

#include <fstream>
#include <string>
void test01()
{
    ifstream ifs;
    ifs.open("test.txt", ios::in);

    if (!ifs.is_open())
    {
        cout << "文件打开失败" << endl;
        return;
    }

    //第一种方式
    //char buf[1024] = { 0 };
    //while (ifs >> buf)
    //{
    //    cout << buf << endl;
    //}

    //第二种
    //char buf[1024] = { 0 };
    //while (ifs.getline(buf,sizeof(buf)))
    //{
    //    cout << buf << endl;
    //}

    //第三种
    //string buf;
    //while (getline(ifs, buf))
    //{
    //    cout << buf << endl;
    //}

    char c;
    while ((c = ifs.get()) != EOF)
    {
        cout << c;
    }

    ifs.close();


}

int main() {

    test01();

    system("pause");

    return 0;

可以看到ifs>>buf作为while循环判断式与cin的用法是一样的!并且还有ifs.getline等等,这说明我们将ifstream与cin做对比是可以的!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值