#include <iostream>
#include <fstream>
using namespace std;
int main(){
ifstream in;
in.open("test.txt");
if(!in){
cout << "open file failed" << endl;
return 0;
}
char x;
while(in >> x){
cout << x;
}
cout << endl;
//--------------------
ofstream out;
out.open("test1.txt");
if(!out){
cout << "open file failed" << endl;
return 0;
}
for(int i = 0; i < 10; i++){
out << i;
}
cout << endl;
out.close();
return 0;
}
常见的打开模式:
ios::in–打开一个可读取文件
ios::out–打开一个可写入文件
ios:binary –以二进制的形式打开一个文件。
ios::app –写入的所有数据将被追加到文件的末尾
ios::trunk –删除文件原来已存在的内容
ios::nocreate –如果要打开的文件并不存在,那么以此叁数调用open函数将无法进行。
ios:noreplece –如果要打开的文件已存在,试图用open函数打开时将返回一个错误。
#include <iostream>
#include <fstream>
using namespace std;
int main(){
fstream fp("test.txt",ios::in | ios::out);
if(!fp){
cout << "open file failed" << endl;
return 0;
}
fp << "WelcomeToMyHome!";
static char str[100];
fp.seekg(ios::beg);//使文件指针指向文件头
fp >> str;
cout << str << endl;
fp.close();
return 0;
}