fstreamの効率のいい使い方
Posted: 2009年2月25日(水) 12:07
どうも御世話になっております。
とりあえずソースからいきます。
どこに問題があるのでしょうか?
それと、途中に挿入するような場合はわざわざこんな風にしないといけないのでしょうか?
もっと簡単にはできないのでしょうか(std::ios::appだと最後にしか書き込めないので…)?
効率のいい使い方等ありましたら、よろしくお願いします。
とりあえずソースからいきます。
#include <tchar.h> #include <windows.h> #include <iostream> #include <string> #include <fstream> // tchar.h 的に使えるようにする #ifdef _UNICODE #define _tcout std::wcout #define _tstring std::wstring #define _tfstream std::wfstream #else #define _tcout std::cout #define _tstring std::string #define _tfstream std::fstream #endif // prototype void InsertText(_tstring dir, DWORD pos, _tstring txt); // main int _tmain(int argc, TCHAR* argv[/url], TCHAR* envp[/url]) { std::locale loc = std::locale(); loc = std::locale(loc, "japanese", std::locale::ctype); std::locale::global(loc); // テキストを任意の位置で追記 InsertText(_T("書き出し.txt"), 6, _T("test")); return 0; } void InsertText(_tstring dir, DWORD pos, _tstring txt) { // ファイルストリーム _tfstream fs(dir.c_str(), std::ios::in | std::ios::out); // pos _tfstream::pos_type insert_pos = pos; // 一時的な保持用 _tstring str1, str2, tmp; while(true) { fs >> tmp; str1 += tmp; if(fs.tellg() > insert_pos) { // pos位置までに削る if(str1.size() > pos) { // char str1 = str1.substr(0, pos); } else { // wchar_t str1 = str1.substr(0, (DWORD)(pos/2)); } // pos位置へ移動 fs.seekg(insert_pos); while(!fs.eof()) { // 終わりまで読み込む fs >> tmp; str2 += tmp; } break; } } // debug _tcout << str1 << txt << str2 << std::endl; // 最初へ移動 fs.seekp(0, std::ios::beg); fs << str1 << txt << str2 << std::endl; }少々長くなりましたが、テキストを任意の位置に追加(挿入)するようなプログラムを書いたつもりなのですが、debugと書いたcoutによる出力では、ちゃんとできていることが確認できるのですが、最後のfsによる書き込みが正常に出来ていないようです。
どこに問題があるのでしょうか?
それと、途中に挿入するような場合はわざわざこんな風にしないといけないのでしょうか?
もっと簡単にはできないのでしょうか(std::ios::appだと最後にしか書き込めないので…)?
効率のいい使い方等ありましたら、よろしくお願いします。