C++入門(4):文件讀寫

C++入門(4):文件讀寫

對文件進行讀寫要包含下面的頭文件:
#include <fstream>
ofstream: 輸出文件流,文件名可以是絕對路徑名或相對路徑名
ifstream: 輸入文件流

std::ofstream  fileOutput0(".\\fileTest\\file0.txt");   //將fileOutput0變量與一個特定的文件關聯在一起
if(fileOutput0.is_open())    //使用is_open()函數來確認這個文件已被打開,或者使用fileOutput0.good()函數確認
{
    std::cout << "The file has been opened successfully!" << std::endl;
    fileOutput0 << "Please write something...\n" ;  //向文件寫數據
    fileOutput0.close();    //及時關閉文件
}
else
{
    std::cout << "The file cannot be opened successfully!" << std::endl;
    return 1;              //如果不能打開,返回一個狀態
}

如果使用上面的方法定義了一個文件變量fileOutput0,則即使關閉了這個文件,在程序以後的變量定義中也都不能再使用fileOutput0來定義另外一個文件變量了。
爲了解決這個問題,可以使用open()函數:它用同一個文件變量打開多個文件,即先打開一個文件並把它關聯到fileOutput變量,用完之後關閉它,然後再打開一個文件並把它關聯到fileOutput變量。

std::ofstream fileOutput1;  //可以先創建一個ofstream類型的變量,再調用open()函數打開一個文件
fileOutput1.open(".\\fileTest\\file1.txt") ;
fileOutput1 << "The first time to use the parameter! \n";
fileOutput1.close();
fileOutput1.open(".\\fileTest\\file2.txt") ;      //關閉之後可以使用這個文件變量打開另一個文件
fileOutput1 << "The second time to use the parameter! \n";
fileOutput1.close();

給現有文件增加數據:

std::string user;
std::ofstream fileOutput2(".\\fileTest\\file0.txt", std::ios::app); //給現有文件增加數據
if(fileOutput2.is_open()) //打開文件時進行檢測是很有用的,可以避免很多不必要的錯誤
{
    std::cout << "What do you want to add to the file!" << std::endl;
    std::getline(std::cin, user);                //先讀入一行數據到變量user
    fileOutput2 << user << std::endl;            //再把user寫入文件
    fileOutput2.close();
}
else
{
    std::cout << "The file cannot be opened successfully!" << std::endl;
    return 1;
}

從文件讀取數據:
也可以利用字符串拼接操作符,把一個完整的文件讀入一個大字符串。

std::string line,entireTxt;
std::cout << entireTxt;   //entireTxt初始化是個空串
std::ifstream fileInput3(".\\fileTest\\file0.txt"); //定義一個ifstream類型的變量表示讀取,從文件讀取數據時,文件必須已經存在
if(fileInput3.is_open())  //文件成功打開之後,可以進行讀取數據的操作
{
    while(std::getline(fileInput3,line))         //getline()用於文件,表示從特定文件讀取一行數據,把數據賦給變量line
    {
        entireTxt += line;                       //字符串拼接
    }
    fileInput3.close();                         //一定要及時關閉文件
    std::cout << entireTxt;
}
else
{
    std::cout << "The file cannot be opened successfully!" << std::endl;
    return 1;
}

C++入門(3):輸入、輸出

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章