在C++中 , 若我們想要開檔(write file) , 讀檔(read file) , 可以利用ofstream與ifstream來達成我們想要的目的.
ofstream :
int main()
{
ofstream fout("file_B.txt");
fout<<"output string";
fout.close(); // 關閉檔案
return 0;
}
then , the string , "output string" , will be write into the file named file_B.txt.
ifstream :
#include <fstream>
using namespace std;
int main ()
{
ifstream ifs ( "test.txt" , ifstream::in );
string str;
while (ifs >> str)
{
cout << str << endl;
}
ifstream ifs2 ( "test.txt" , ifstream::in );
while (getline(ifs2 , str))
{
cout << str << endl;
}
ifs.close();
return 0;
}
the instruction , ifs >> str , will read a word one time.
if the content of test.txt is "this is a test file." , the output will be
this
is
a
test
file.
and the instruction , getline(ifs2 , str) , will read a line one time ,
so the outupt will be
this is a test file.
ref : http://finalfrank.pixnet.net/blog/post/22540420-c%2B%2B%E9%96%8B%E8%AE%80%E6%AA%94
ref : http://www.cplusplus.com/reference/iostream/ifstream/ifstream/