系统:Mac OS
编程工具:Sublime Text 2
1.保存至文件
//fstream包含ifstream,ofstream,fstream类,继承于istream,ostream类
#include <fstream>
using namespace std;
int main(){
ofstream saveFile("word.txt");//如果该文件存在,则替换;如果不存在,则创建
saveFile << "This is a test file for saving file!"<<endl;
saveFile << "Hello world!"<<endl;
saveFile.close();
return 0;
}
2.读取文件中内容
方式一:
//fstream包含ifstream,ofstream,fstream类,继承于istream,ostream类
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ofstream saveFile("word.txt");//如果该文件存在,则替换;如果不存在,则创建
saveFile << "This is a test file for saving file!"<<endl;
saveFile << "Hello world!"<<endl;
saveFile.close();
ifstream openFile("word.txt");
char ch;
while(!openFile.eof()){
openFile.get(ch);//逐次读取1个字符,直到文档介绍
cout << ch;
}
openFile.close();
return 0;
}
//fstream包含ifstream,ofstream,fstream类,继承于istream,ostream类
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ofstream saveFile("word.txt");//如果该文件存在,则替换;如果不存在,则创建
saveFile << "This is a test file for saving file!"<<endl;
saveFile << "Hello world!"<<endl;
saveFile.close();
//读取文件方式一:
//ifstream openFile("word.txt");
//读取文件方式二:利用open函数
ifstream openFile;
openFile.open("word.txt");
char ch;
while(!openFile.eof()){
openFile.get(ch);//逐次读取1个字符,直到文档介绍
cout << ch;
}
openFile.close();
return 0;
}
输出为:
This is a test file for saving file!
Hello world!