C++文件操作
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()

{
const char filename[] = "mytext.txt";
ofstream o_file;
ifstream i_file;
string out_text;
//寫
o_file.open(filename);
for (int i = 1; i <= 10; i++)
{
o_file << "第" << i << "行"<<endl; //將內容寫入到文本文件中
}
o_file.close();
//讀
i_file.open(filename);
if (i_file.is_open())
{
while (i_file.good())
{
i_file>> out_text; //將讀取的內容存儲到變量out_text中
cout << out_text << endl; //在控制臺輸出讀取的內容。為什么最后一行的內容會出現兩次
}
}
else
cout << "打開文件:" << filename << " 時出錯!";
i_file.close();
system("PAUSE");
return 0;
}

preheader:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])

{
const char filename[]="test.doc";
ofstream o_file;/**//* 輸出流:將數據從內存輸出其中ofstream是將數據輸出到文件,因此對于文件來說是“寫”*/
ifstream i_file;/**//*將數據輸入到內存,其中ifstream是說輸入的數據在文件中,因此對于文件來說是“讀”*/
string out_text;
//寫
o_file.open(filename);
for(int i =0;i<=12;i++)
{
o_file<<"第"<<i<<"行\(zhòng)n";//將內容寫入文本
}
o_file.close();
//讀
i_file.open(filename);
if(i_file.is_open())
{
while(i_file>>out_text)
{
cout << out_text << endl;
}
}
else
cout<<"打開文件:"<<filename<<"時出錯!";
i_file.close();
system("PAUSE");
return 0;
} 

