C++ STL ofstream ifstream ファイル操作 ファイル入出力 標準ライブラリ サンプルメ[ス
C++の標準ライブラリSTLを利用してファイル入出力を行うサンプルです。 このサンプルでは、 ofstream や ifstream というライブラリを利用しています。 -- サンプルメ[スコード #include <iostream> #include <fstream> #include <string> using namespace std; int main() { string filename = "test.txt"; string str1; string str2; // 書き込み用ファイルストリーム ofstream fout; // 読み込み用ファイルストリーム ifstream fin; /* * ファイルへ書き込む。 */ // ファイルオープン fout.open(filename.c_str()); // ファイルをオープンできなければエラー if (!fout.is_open()) { cout << "ファイルをオープンできません" << endl; return -1; } // 書き込み fout << "ああああ" << endl; fout << "いいいい" << endl; // ファイルクローズ fout.close(); /* * ファイルから読み込む。 */ // ファイルオープン fin.open(filename.c_str()); // ファイルをオープンできなければエラー if (!fin.is_open()) { cout << "ファイルをオープンできません" << endl; return -2; } // 読み込んだ文字列をstrへ代入 fin >> str1; // 1行目 fin >> str2; // 2行目 // 出力 cout << str1 << endl; // 1行目 cout << str2 << endl; // 2行目 // ファイルクローズ fin.close(); return 0; } -- 出力結果 ああああ いいいい ※ このexeと同じ階層に test.txt っていうファイルが生成されているはずです。
http://goodjob.boy.jp/chirashinoura/id/97.html
作成日: 2006-08-31 16:58:52
最終更新日: 2006-08-31 16:58:52
▲このページの上へ管理人: ぶらざーほわいつ 連絡