文件读写
http://www.runoob.com/cplusplus/cpp-files-streams.html
#include <iostream> #include <fstream> // 文件操作库文件 #include <string> using namespace std; // 写文件 void fileWrite(string filepath, string filename, char content[]) { // 文件输出流 ofstream outfile; // 打开文件 outfile.open(filepath + filename, ios::app); // 写入文件 outfile << content << endl; // 关闭文件,释放资源 outfile.close(); } // 读文件 void fileRead(string filepath, string filename) { // 文件输入流 ifstream infile; // 打开文件 infile.open(filepath + filename, ios::in); // 读出文件 //infile >> data; 只能读一行,遇到空格或回车就停止不读了 cout << "******* Read from file:\n" << infile.rdbuf() << endl; // 关闭文件,释放资源 infile.close(); } int main() { string filepath = "./file/"; string filename = "test.txt"; char content[100]; string filedata; // 文件写入 cout << "******* Enter your name:"; cin.getline(content, 100); // 用户输入的数据放到content中 fileWrite(filepath, filename, content); cout << "******* Enter your age:"; cin >> content; // 用户输入的数据放到content中 cin.ignore(); fileWrite(filepath, filename, content); // 文件读出 fileRead(filepath, filename); system("pause"); return 0; }
运行: