1.使用文件流写文本文件:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string name;
int age;
ofstream offile;//文件输出流(写文件)
offile.open("user1.txt",ios::out | ios::app);//打开文件user1.txt
while (1)
{
cout << "请输入姓名:";
cin >> name;
if (cin.eof()) {
break;
}
offile << name << "\t";
cout << "请输入年龄:";
cin >> age;
offile << age << endl;
}
offile.close();//关闭文件
system("pause");
return 0;
}
2.使用文件流读文本文件:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string name;
int age;
ifstream iffile;
iffile.open("user1.txt", ios::in );
while (1)
{
iffile >> name;
if (iffile.eof()) {
break;
}
cout << name << "\t";
iffile >> age;
cout << age << endl;
}
iffile.close();
system("pause");
return 0;
}
3.使用文件流写二进制文件:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string name;
int money;
ofstream offile;
offile.open("user.txt",ios::binary | ios::out);
while (1)
{
cout << "请输入名字:";
cin >> name ;
if (cin.eof()) {
break;
}
offile << name << "\t";
cout << "请输入财产:";
cin >> money;
offile.write((char*)&money, sizeof(money)) << endl;
}
offile.close();
system("pause");
return 0;
}
4.使用文件流读二进制文件:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string name;
int money;
ifstream infile;
infile.open("user.txt",ios::binary | ios::in);
while (1)
{
infile >> name;
if (infile.eof()) {
break;
}
cout << name << "\t";
//跳过中间的制表符
char tmp;
infile.read(&tmp,sizeof(tmp));
infile.read((char *)&money,sizeof(money));
cout << money << endl;
}
infile.close();
system("pause");
return 0;
}
5.按指定格式写文本文件:
#include <fstream> //文件输入/输出流
#include <sstream> //字符串输入/输出流
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
int age;
ofstream offile; //文件输出流(写文件)
offile.open("user.txt",ios::out | ios::trunc); //打开文件
while (1)
{
cout << "请输入名字:";
cin >> name;
if (cin.eof()) {
break;
}
cout << "请输入年龄:";
cin >> age;
stringstream str; //字符串输入/输出流
str << "姓名:" << name << "\t年龄:" << age << endl;
offile << str.str();//把字符串输入/输出流转换为字符串
}
offile.close(); //关闭文件
system("pause");
return 0;
}
6.按指定格式读文本文件:
#include <fstream> //文件输入/输出流
#include <sstream> //字符串输入/输出流
#include <iostream>
#include <string>
using namespace std;
int main() {
string line;
char name[32] ;
int age;
ifstream infile;
infile.open("user1.txt");
while (1)
{
getline(infile, line);
if (infile.eof()) {
break;
}
sscanf_s(line.c_str(), "姓名:%s 年龄:%d", name, sizeof(name), &age);
//姓名和年龄这里的":"要注意,写的时候是中文字符的冒号,读的时候也要写成中文字符的,否则结果会出现乱码
cout << "姓名:" << name << "\t\t年龄:" << age << endl;
}
infile.close();
system("pause");
return 0;
}