c++对文件的操作使用数据流来实现的
对文件操作一般都是用里面的类来实现的
一般常用:
ifstream:对文件输入(读文件)
ofstream :对文件输出(写文件)
fstream : 对文件输入或输出
文件的输入:先用ifstream类定义一个对象
在用这个对象的方法打开文件,然后就可以把数据通过这个对象输入到文件中了(想象成一个管子,插到文件中,然后把数据流进去)最后不要忘记关闭文件。
#include<Windows.h>
#include<iostream>
#include<fstream>
using namespace std;
int main() {
ifstream infile;
infile.open("小猪猪.txt");
string name;
int age;
while (1) {
infile >> name;
if (infile.eof()) {
break;
}
cout << name << "\t";
infile >> age;
cout << age << endl;
}
infile.close();
system("pause");
return 0;
}
也可以用fstream 比如注释,但是用这个定义就系统就不知道你是干什么,所以需要指定操作
文件输出:方法与文件输入一样,不过就是用了ofstream类 ,并且因为通过空格来区分的,所以他会一个一个读取
#include<Windows.h>
#include<iostream>
#include<fstream>
using namespace std;
int main(){
ofstream outfile;
//fstream outfile;
string name;
int age;
//outfile.open("小猪猪.txt", ios::out | ios::trunc );
outfile.open("小猪猪.txt");
while (1) {
cout << "请输入姓名[输入ctrl+z结束]:";
cin >> name;
if (cin.eof()) {
break;
}
cout << "请输入年龄:";
cin >> age;
outfile << name << "\t" << age << endl;
}
outfile.close();
system("pause");
return 0;
}