IO设备:文件、终端(dos黑框框)、特殊的数据类型(streamstring)
C++中的输入输出流是靠定义好的类库来操作的
头文件:fstream
ofstream:读写
istream:读操作
of
#include
#include
#includeusing namespace std;int main() {ofstream outfile;string name;int age;cin >> name >> age;outfile.open("C:/Users/98207/desktop/test.txt", ios::out); // 写入文件,没有文件会新疆,默认文件是截断的outfile << name << endl;outfile << age;outfile.close();return 0;
}
程序:
#include
#include
#include
#includeusing namespace std;int main() {ifstream infile;string str;int age;infile.open("C:/Users/98207/desktop/test.txt", ios::in); // 读取文件while (1) {if (infile.eof()) {break;}infile >> str;cout << str << endl;;// getline(infile, str);// cout << str << endl;}infile .close();return 0;
}
结果:
bian
12
写入文件
#include
#include
#include
#includeusing namespace std;int main() {string name;int age;fstream outfile;outfile.open("C:/Users/98207/Desktop/test2.txt", ios::out);cin >> name >> age;outfile << name << endl;outfile << age;outfile.close();return 0;
}
读取文件
#include
#include
#include
#includeusing namespace std;int main() {string str;fstream infile;infile.open("C:/Users/98207/Desktop/test2.txt", ios::in);while (1) {if (infile.eof()) {break;}infile >> str;cout << str << endl;}infile.close();return 0;
}
二进制和文本写区别在于数字二进制数字把实际字节数写入进去。
比如9,那么写入的是4个char字符0009至于大小端看电脑。
#include
#include
#includeusing namespace std;int main() {fstream outfile;char name[20];int age;// 为什么保存格式是dat,因为使用文本格式会按照文本格式解析outfile.open("C:/Users/98207/Desktop/1.dat", ios::trunc | ios::out | ios::binary);cin >> name >> age;outfile << name << '\t';outfile.write((char*)&age, sizeof(age)); // 二进制写outfile.close();return 0;
}
#include
#include
#includeusing namespace std;int main() {fstream infile;char name[20];char temp;int age;infile.open("C:/Users/98207/Desktop/1.dat", ios::in | ios::binary);infile >> name;infile.read((char*)&temp, sizeof(temp)); // 丢弃制表符infile.read((char*)&age, sizeof(age));cout << name << '\t' << age << endl;infile.close();return 0;
}
#include
#include //ofstream
#include // stringstreamusing namespace std;int main() {stringstream ret;ofstream outfile;string name;int age;outfile.open("C:/Users/98207/Desktop/test2.txt", ios::out | ios::trunc);while (1) {cin >> name >> age;if (cin.eof()) {break;}ret << name << "\t\t\t" << age << endl; // ret会累积// outfile << ret.str();// ret.clear();}outfile << ret.str();outfile.close();return 0;}
#include
#include
#include // getline, stringusing namespace std;int main() {fstream infile;string str;char name[20];int age;infile.open("C:/Users/98207/Desktop/test2.txt", ios::in);while (1) {getline(infile, str);if (infile.eof()) {break;}sscanf_s(str.c_str(), "%s %d", name, sizeof(name), & age); // 这里的参数只能是char类型,这里的空格会替换文件的制表符或者空格cout << name << "\t\t\t" << age << endl;}infile.close();return 0;
}
这里常用的就是is_open()和eof()
未完成