使用IO流进行文件读取
对文件操作类包括ofstream、ifstream和fstream。其中fstream为iostream(由istream和ostream派生)的派生类,ofstream为ostream派生类,ifstream为istream派生类,从而对文件进行读写操作。
1、写文件:当有该文件时打开该文件,没有时自行创建。可使用
ofstream LogFile("d://test.txt", ios::app);
if(!LogFile)//或者写成myfile.fail()
{
cout<<"文件读错误!";
system("pause");
}
LogFile << "Log Message Received:" << endl;
LogFile << ""tTime_Stamp: " << ACE_TEXT_ALWAYS_CHAR (ACE_OS::ctime (&epoch)) << flush;
第二种调用方式:
ofstream LogFile;
LogFile.open("d://test.txt", ios::app);
LogFile << "Log Message Received:" << endl;
2、读文件:单个字符读到ch;整个文件内容读到字符串content;
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream myfile;
myfile.open("d:""1.txt",ios::in);
if(!myfile)
{
cout<<"文件读错误";
exit(1);
}
char ch;
string content;
while(myfile.get(ch))
{
content += ch;
cout<<ch<<endl;//cout<<ch;这么写也是可以的
}
myfile.close();
cout<<content<<endl;
}
浙公网安备 33010602011771号