C++基礎::檔案流

Inside_Zhang發表於2015-11-19

構造及檔案開啟與否的判斷

  • 構造

    const std::string filename;
    std::ofstream ofs(filename);
                        // C++11
    std::ofstream ofs(filename.c_str());
                        // before C++11
  • 檔案開啟成功與否的判斷

    std::ifstream ifs(filename);
    if (!ifs)
                        // if (!ifs.good())
    {
        std::cerr << "cannot open the input file \"" << filename << "\"" << std::endl;
        exit(EXIT_FAILURE);
    }

從檔案流中讀資料的方式

std::ifstream ifs(filename);
assert(ifs.good());
  • 逐字元

    char c;
    while (ifs.get())
        std::cout << c;
  • 逐行

    std::string line;
    while (std::getline(ifs, line, '\n'))
                            // std::getline()的標頭檔案在 <string>
        std::cout << line << std::endl;
  • 逐單詞(以空格為分割)讀取

    std::string word;
    while (ifs >> word)
        std::cout << word << std::endl;

臨時建立的檔案流

std::ofstream("./1.txt") << "hello";
std::ofstream("./1.txt", std::ios::app) << " world!" << std::endl;

std::ifstream ifs("./1.txt");
assert(ifs.good());
std::string line;
while (std::getline(ifs, line, '\n'))
    std::cout << line << std::endl;

相關文章