写文件
/*
创建一个文件,把姓名,年龄和薪资写进去;
*/
#include <iostream>
#include <fstream>//文本操作的头文件
using namespace std;
int main(void) {
string name;
int age;
int salary;
ofstream outfile;//以写的方式创建一个文本
infile.open("test.txt");//打开文本
while (1){
cout << "请输入名字:";
cin >> name;
cout << "请输入年龄:";
cin >> age;
cout << "请输入薪资:";
cin >> salary;
if (cin.eof()) {//判断输入信息的结束符
break;
}
//把输入的信息写到文本里去
outfile << name << "\t" << age << "\t" << salary << endl;
}
outfile.close();//关闭文本
system("pause");
return 0;
}
读文件
/*
把test.txt文本的信息读出来
*/
#include <iostream>
#include <fstream>//文本操作的头文件
using namespace std;
int main(void) {
string name;
int age;
int salary;
ifstream infile;//以读的方式创建一个变量
infile.open("test.txt");//打开需要读取的文件
while (true){
//把文件的信息读取出来
infile >> name >> age >> salary;
if (infile.eof()) {//判断文件是否读完
break;
}
//打印文件的信息到控制台
cout << name << "\t" << age << "\t" << salary << endl;
}
infile.close();//关闭文件
system("pause");
return 0;
}
以二进制写文件
#include <iostream>
#include <fstream>//文本操作的头文件
using namespace std;
int main(void) {
string name;
int age;
int salary;
fstream outfile;//以读的方式创建一个变量
outfile.open("test.bat",ios::out|ios::trunc|ios::binary);//以二进制打开文件
while (true){
cin >> name >> age >> salary;
outfile << name;
outfile.write((char*)&age, sizeof(age));//以二进制写入(write)
outfile.write((char*)&salary, sizeof(salary));
if (cin.eof()) {//判断文件是否读完
break;
}
}
outfile.close();//关闭文件
system("pause");
return 0;
}
以二进制读文件
#include <iostream>
#include <fstream>
using namespace std;
int main(void) {
string name;
int age;
int salary;
fstream file;
file.open("test.dat",ios::in|ios::binary);//以二进制的方式读取
while (true) {
//判断是否读到结束符
file >> name;
if (file.eof()) {
break;
}
char tmp;
file.read(&tmp,sizeof(tmp));//跳过制表符
cout << name << "\t";
file.read((char*)&age, sizeof(age));//以二进制读取(read)
file.read((char*)&salary, sizeof(salary));
cout << age << "\t" << salary << endl;
}
file.close();
system("pause");
return 0;
}
指定格式写文件
#include <iostream>
#include <fstream>//文本操作的头文件
#include <sstream>
using namespace std;
int main(void) {
string name;
int age;
int salary;
ofstream file;//以读的方式创建一个变量
file.open("demo.txt");//打开需要读取的文件
while (true) {
cin >> name >> age >> salary;
if (cin.eof()) { break; }
//使用流的格式把数据写到文本里去
stringstream s;
s << name << "\t"<< age << "\t" << salary << endl;
file << s.str();
}
file.close();//关闭文件
system("pause");
return 0;
指定格式读文件
#include <iostream>
#include <fstream>//文本操作的头文件
#include <sstream>
using namespace std;
int main(void) {
string name;
int age;
int salary;
ifstream file;
char line[64]=" ";
file.open("demo.txt");
if (!file) {
cout << "打开失败" << endl;
exit(1);
}
while (true) {
getline(file, name);
if (file.eof()) { break; }
sscanf_s(name.c_str(), "%s %d %d", line, sizeof(line), &age, &salary);
cout <<string(line)<<"\t" << age <<"\t"<< salary << endl;
}
file.close();
system("pause");
return 0;
}