C++ファイルフロー操作

6640 ワード

1.ファイルを書く
ofstream outfile("file_name",open_mode);

開くモードはデフォルトで、デフォルトでは毎回ファイルの元のデータを消去し、今回の内容を書き込むことができます.
追加内容採用:ios_base::app
ofstream outfile("out_file.txt",ios_base::app);

if (!outfile)

    cerr << "Oops! Unable to save data!" << endl;

else

    outfile << "username" << ' '

    << 18<< ' '

    << 18<< endl;

 2.ファイルを読む
ifstream infile("file_name",open_mode);
    ifstream infile("out_file.txt");

    string user_name;

    int nc_all;

    int nc_rgt;



    while (infile >> user_name)

    {

        infile >> nc_all >> nc_rgt;

        if (user_name == "username")

        {

            cout << "Welcome " << user_name << " back!" << endl;

            cout << "Your current score is " << nc_rgt << " out of " << nc_all << " " << endl;

            cout << "Good Luck!" << endl;

        }

    }

3.同じファイルを読み書きする
fstream iofile("file_name",open_mode_1|open_mode_2);

同じファイルを読み書きするには、ファイルが追加モードの場合、ファイルフローポインタがファイルの末尾にあり、ファイルフローポインタの位置(seekg()関数)をタイムリーに変更することに特に注意してください.
    fstream iofile("test.txt",ios_base::app|ios_base::in);

    if (!iofile)

        cerr << "Oops! Unable to open the file!" << endl;

    else

    {

        cout << "Success!" << endl;

        iofile << "test" << ' ' << "100" << ' ' << "100" << endl;



        iofile.seekg(ios::beg);

        string user_name;

        string right;

        string all;

        while (iofile >> user_name)

        {

            iofile >> right >> all;

            cout << "Your name is " << user_name << endl;

            cout << "Your score is " << right << " out of " << all << endl;

        }

    }