使用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文件內容
這裏寫圖片描述
輸出
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章