进行文件I/O操作的时候要使用
下面是测试代码 创建文件并往文件中写入内容
当文件夹中没有下面的文件时会创建,并且会覆盖原文件重新写入
一般是创建在编译器的那个 文件夹里
- #include<iostream>
- #include<strstream>
- #include<fstream>
- #include<iomanip>
- using namespace std;
- int main() {
- /*
- ofstream ofile;
- cout << "create file1" << endl;
- ofile.open("test.txt");
- if (!ofile.fail())
- {
- ofile << "name1" << " ";
- ofile << "sex1" << " ";
- ofile << "age1" << " ";
- ofile.close();
- cout << "create file2" << endl;
- ofile.open("test2.txt");
- if (!ofile.fail()) {
-
- ofile << "name2" << " ";
- ofile << "sex2" << "";
- ofile << "age2" << "";
- ofile.close();
-
-
- }
2:下面的测试代码用了ifstream和ofstream对象实现读写文件的功能
用户手动输入5次数据 程序把它写入文件中 然后再打开
- #include<iostream>
- #include<strstream>
- #include<fstream>
- #include<iomanip>
- using namespace std;
- int main(){
- char buf[128];
- ofstream ofile("test.txt");
- for (int i = 0; i < 5; i++) {
- memset(buf, 0, 128);//输入五次数据 程序把这五次数据写入文件中
- cin >> buf;
- ofile << buf;
-
-
- }
-
- ofile.close();//关闭
- ifstream ifile("test.txt");//然后再用ifstream打开
- while (!ifile.eof()) {
-
- char ch;
- ifile.get(ch);
- if (!ifile.eof())
- cout << ch;
- }
- cout << endl;
- ifile.close();
- }
3:对二进制文件的读写 要用 ios::binary模式 读取需要read方法 写则需要write方法
- #include<iostream>
- #include<strstream>
- #include<fstream>
- #include<iomanip>
- using namespace std;
- int main(){
- char buf[50];
- fstream file;
- file.open("test.dat", ios::binary | ios::out);
- for (int i = 0; i < 2; i++) {
- memset(buf, 0, 50);
- cin >> buf;
- file.write(buf, 50);//二进制写要用 write方法
- file << endl;
- }
- file.close();
- file.open("test.dat", ios::binary | ios::in);
- while (!file.eof())
- {
- memset(buf, 0, 50);
- file.read(buf, 50);//二进制读取要read方法
- if (file.tellg() > 0)
- cout << buf;
-
-
- }
- cout << endl;
- file.close();
- return 0;
- }
4:文件的追加
在写入文件时 你可以不一次性写入全部数据 而是一部分一部分写 即不会覆盖前面的内容
测试代码如下
- #include<iostream>
- #include<fstream>
- using namespace std;
- int main() {
- /*
- ofstream ofile("test.txt", ios::app);
- if (!ofile.fail()) {
- cout << "start write" << endl;
- ofile << "mary ";
- ofile << "girl ";
- ofile << "24 ";
-
-
-
-
- }
- else
- cout << "打不开啊";
- }
5:eof成员函数可以用来判断文件结尾
在指定位置读写文件 用到了文件指针 可以输出你要求的位置的信息

测试代码如下
- #include<iostream>
- #include<fstream>
- using namespace std;
- int main() {
- ifstream ifile;
- char cfileselect[20];
- cout << "输入文件名:";
- cin >> cfileselect;
- ifile.open(cfileselect);
- if (!ifile)
- {
- cout << cfileselect << "打不开" << endl;
- return 0;
-
- }
- ifile.seekg(0, ios::end);
- int maxpos = ifile.tellg();
- int pos;
- cout << "输入查找的位置:";
- cin >> pos;
- if (pos > maxpos) {
- cout << "is over file lenght" << endl;
- }
- else
- {
- char ch;
- ifile.seekg(pos);
- ifile.get(ch);
- cout << ch << endl;
- }
- ifile.close();
- return 1;
-
-
-
-
-
-
-
- }