ファイルオープンモード †
以下はファイルの末尾にテキストを追加するサンプル #include <fstream> int main() { std::ofstream ofs( "test.txt", std::ios::out | std::ios::app ); ofs << "append test" << std::endl; return 0; } ファイルに一行ずつ書き込み †#include <iostream> #include <fstream> #include <string> int main(int argc, char* argv[]) { // ファイルから入力ストリームの初期化 std::ifstream ifs("/home/test/test.log"); std::string line; while (std::getline(ifs, line)) { // ファイルの中身を一行づつ表示 std::cout << line << std::endl; } // ファイルへ出力ストリームの初期化 std::ofstream ofs("C:¥¥home¥¥nazo.txt"); // ファイルに1行ずつ書き込み ofs << "ham" << std::endl; ofs << "egg" << std::endl; ofs << "spam" << std::endl; return 0; } ファイルの拡張子を取得する †string getFileExt(const string& filePath) { std::size_t found = filePath.find_last_of(".") + 1; return filePath.substr(found,filePath.length()); } //呼出 string ext = getFileExt(fullname); cout << ">>>> ext = " << ext << endl; ファイル存在するかの判断 †#include <sys/stat.h> #include <unistd.h> #include <string> inline bool exists_test0 (const std::string& name) { ifstream f(name.c_str()); return f.good(); } inline bool exists_test1 (const std::string& name) { if (FILE *file = fopen(name.c_str(), "r")) { fclose(file); return true; } else { return false; } } inline bool exists_test2 (const std::string& name) { return ( access( name.c_str(), F_OK ) != -1 ); } inline bool exists_test3 (const std::string& name) { struct stat buffer; return (stat (name.c_str(), &buffer) == 0); } 毎回100000回を呼出して、5回実行した結果です。 Method exists_test0 (ifstream): **0.485s** Method exists_test1 (FILE fopen): **0.302s** Method exists_test2 (posix access()): **0.202s** Method exists_test3 (posix stat()): **0.134s** あなたのお住まいの地域で最安のブロードバンド選び コメント: |