VC

ファイルオープンモード

フラグ説明
out書き込み専用に開く。デフォルト。
app追記用に開く。
ateファイルを開くと、自動的に末尾に移動する。
truncファイルを開くと、以前の内容を全て削除する。
binary特殊な文字を置換しない。

以下はファイルの末尾にテキストを追加するサンプル

#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**


あなたのお住まいの地域で最安のブロードバンド選び

コメント:



(画像の文字列を入力して下さい)

トップ   編集 凍結 差分 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2019/12/02 (月) 12:43:27 (1627d)

yVoC[UNLIMITȂ1~] ECirŃ|C Yahoo yV LINEf[^[Ōz500~`I


z[y[W ̃NWbgJ[h COiq 萔O~ył񂫁z COsیI COze