C++文件操作練習

  • 1.概念
    標準庫 fstream定義了3個數據類型如下:
    ofstream:該數據類型表示輸出文件流,用於創建文件並向文件寫入信息。
    ifstream:該數據類型表示輸入文件流,用於從文件讀取信息。
    fstream:該數據類型通常表示文件流,且同時具有 ofstream 和 ifstream 兩種功能,這意味着它可以創建文件,向文件寫入信息,從文件讀取信息。

  • 2.demo代碼如下:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

void fileTest();

int main ()
{
    fileTest();
    return 0;
}

/**
 * 文件測試
 */
void fileTest(){
    string filepath = "D:\\C++Test\\test.txt";
    string file_name = "test.txt";
    //建立一個讀取的ifile,由於讀取 input.txt中的內容  
    cout << file_name.c_str() << endl;
    ifstream ifile(filepath.c_str());

    if (! ifile)
    {
        cerr << "oops! unable to open input file: " << file_name << endl;
        return;
    }
    else
    {
        cerr << "!! ok: opened " << file_name << " for input\n";
    }

    //新建一個input.txt.sort文件,用於保存排好序的文字
    //類型是輸出ofile
    file_name += ".sort";
    ofstream ofile( file_name.c_str() );

    if (! ofile)
    {
        cerr << "oops! unable to open output file: " << file_name << endl;
        return;
    }
    else
    {
        cerr << "!! ok: opened " << file_name << " for output\n";
    }


    string word;
    vector<string> text;
    //讀取內容到word至文件末尾
    while (ifile >> word)
    {
        //插入到容器text中
        text.push_back( word );
    }

    if (text.empty())
    {
        cerr << "bummer! input file is empty: bailing out\n";
        return;
    }
    else
    {
        cerr << "!! ok: read " << text.size() << " strings from input\n";
    }
    //排序操作
    sort(text.begin(), text.end());

    int cnt = 0;
    for (vector<string>::iterator iter = text.begin(); iter != text.end(); ++iter )
    {
        //排列格式
        cnt += iter->size() + 1;
        if (cnt > 40)
        {
            ofile << '\n';
            cnt = 0;
        }
        //輸出到ofile中,即input.txt.sort文件中
        ofile << *iter << ' ';
    }

    cout << "ok: wrote sorted strings into " << file_name << endl;

}
  • 3.控制檯輸出如下:

D:\C++Test\cmake-build-debug\C__Test.exe
test.txt
ok: wrote sorted strings into test.txt.sort
!! ok: opened test.txt for input
!! ok: opened test.txt.sort for output
!! ok: read 5 strings from input
Process finished with exit code 0

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