使用std--fstream处理文件

fstream文件操作总结

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

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

包含头文件

 #include 

  1. 使用open( )和close( )打开和关闭文件
#include
#include
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( )函数:第一个参数是要打开的文件的路径和名称(或指定当前路径),第二参数是文件的打开模式。
具体属性可参考网址
使用std--fstream处理文件_第1张图片

其他文件读取方式:

//使用构造函数打开
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
#include
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
#include
#include
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文件内容
这里写图片描述
输出
使用std--fstream处理文件_第2张图片

你可能感兴趣的:(Linux常用操作)