我们经常整些命令台程序,啥cout<<, cin>>之类的.而实际项目中基本上不会要你用cout啥的在屏幕上输出.而在硬盘上读写文件操作倒很多.
假如没用到MFC或者win API咋去读写文件呢.STL中提供了一些类可以让你很方便的读写文件.比较常见有有三个:
fstream :可以写也可以读文件
ofstream: 只能写文件
ifstream:只能读文件
写文件
#include <iostream>
#include <string>
#include <fstream> //记得引用该头文件
using namespace std;
int main()
{
//用fstream来写文件
string filePath = "D:\\arwen.txt";
fstream writeFile;
writeFile.open( filePath, ios::out); //打开文件,如果文件不存在则创建该文件.
writeFile<<"hello arwen."<<endl; //往文件中写入内容,如果打开的文件中之前有内容会被覆盖.如果只想在原有内容上添加内容则要这样打开文件
//writeFile.open(filePath, ios::out | ios::app);
fstream.close();
//用ofstream来写文件
string filePath = "D:\\tmp.txt";
ofstream fileWriteOnly;
fileWriteOnly.open( filePath, ios::out);
fileWriteOnly << "i am temp file"<<endl;
fileWriteOnly.close();
读文件
//用fstream读文件
string filePath = "D:\\arwen.txt";
fstream readFile;
readFile.open( filePath, ios::in);
char ch;
while( readFile.get(ch) )
cout<<ch;
readFile.close();
//用ifstream读文件
string filePath = "D:\\tmp.txt";
ofstream fileReadOnly;
fileReadOnly.open( filePath, ios::in);
while( fileReadOnly.get(ch) )
cout<<ch;
fileReadOnly.close();
return 0;
}
上面读文件是一次读一个char,也可以一次读一行.
例如
string filePath = "D:\\tmp.txt";
ofstream fileReadOnly;
fileReadOnly.open( filePath, ios::in);
char myString[100] = {'0'};
while( fileReadOnly.getline(myString , 1000) ) //第二个参数是缓冲区大小
cout<<myString;