使用std--fstream处理文件

fstream文件操作总结

文件的操作一直在用,在此总结一下:fstream的使用

std::fstream从std::ofstream继承写入文件的功能,从std::ifstream继承读取文件的功能.

包含头文件
 #include <fstream>

  1. 使用open( )和close( )打开和关闭文件
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    fstream myFile;
    //如果不存在即创建新文件
    myFile.open("F:\\wzz_job\\face_confirm\\argv_test\\hello_argv\\helloFile.txt",ios_base::out|ios_base::trunc);

    if (myFile.is_open())
        cout << "open is ok " << endl;
    myFile.close();
    system("pause");
}

输出结果:
这里写图片描述

open( )函数:第一个参数是要打开的文件的路径和名称(或指定当前路径),第二参数是文件的打开模式。
具体属性可参考网址
这里写图片描述

其他文件读取方式:

//使用构造函数打开
fstream myFile("F:\\argv_test\\hello_argv\\helloFile0.txt", ios_base::out | ios_base::trunc);
    // 只想打开文件写入
ofstream myFile("F:\\argv_test\\hello_argv\\helloFile0.txt", ios_base::out);
    // 只想打开文件读取
ifstream myFile("F:\\argv_test\\hello_argv\\helloFile0.txt", ios_base::in);

2.使用open( )创建及写入文本,使用运算符<<

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    fstream myFile;
    //如果不存在即创建新文件
    myFile.open("F:\\wzz_job\\face_confirm\\argv_test\\hello_argv\\helloFile.txt",ios_base::out|ios_base::trunc);
    if (myFile.is_open())
        cout << "open is ok " << endl;
    // 写入文本
    myFile << "hello fstream" << endl;
    cout << "Finished" << endl;
    myFile.close();
    system("pause");
}

3.使用open( )创建及读入文本,使用运算符>>

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
    fstream myFile;
    //如果不存在即创建新文件
    myFile.open("F:\\wzz_job\\face_confirm\\argv_test\\hello_argv\\helloFile.txt",ios_base::in);
    if (myFile.is_open())
        cout << "open is ok " << endl;

    string fileTxt;
    while (myFile.good())
    {
        getline(myFile,fileTxt);
        cout << fileTxt << endl;

    }
    cout << "Finished" << endl;
    myFile.close();
    system("pause");
}

txt文件内容
这里写图片描述
输出
这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值