Fork me on GitHub

C++实现常用的文件操作

①输出到文本文件(txt)

 1 #include<iostream>
 2 #include<fstream>
 3 using namespace std;
 4 int main() {
 5     ofstream doc("test.txt", ios::app);
 6           //ios::app如果没有该文件,生成空文件;
 7           //如果有文件,在文件尾追加
 8 //如果打开失败
 9     if (doc.fail()) {
10         cout << "error" << endl;
11         return 1;
12     }
13     int temp;
14         cin>>temp;
15         doc<<temp;//输出到文件中
16     doc.close();//关闭输出流
17     return 0;
18 }

②从文本文件读入数据

#include<iostream>
#include<fstream>
using namespace std;
int main() {
    ifstream doc("test.txt");
    int t,sum=0;
    if (doc.fail()) {
        cout << "error "<< endl;
    }
    while (doc >> t) {//从文件中读入一个整型数据且不为空
        sum += t;
        cout << t << endl;//输出这个读取到的数值
    }
    cout<<endl<<sum<<endl;
    doc.close();
       return 0;
}

③二进制写文件

 1 #include<iostream>
 2 #include<fstream>
 3 using namespace std;
 4 int main() {
 5     ofstream doc("bfile1.dat",ios::out | ios::app | ios::binary);
 6     if (doc.fail()) {//当文件打开失败时
 7         cout << "error" << endl;
 8     }
 9     float t[] = {1.234,4242.212,4242,314.53,890.2};
10     int count = 0;
11     while (count < 5) {
12         doc.write((char *)&(t[count++]), sizeof(float));
13     }
14     doc.close();
15     return 0;
16 }

④二进制读文件

 1 #include<iostream>
 2 #include<fstream>
 3 using namespace std;
 4 int main() {
 5     ifstream doc("bfile1.dat", ios::in | ios::binary);
 6     if (doc.fail()) {
 7         cout << "error" << endl;
 8     }
 9     float t;
10     while (doc.read((char *)&t, sizeof(float))) {
11         sum += t;
12         cout << t << ends;
13     }
14     cout << endl << sum << endl;
15     doc.close();
16

⑤二进制读写自定义类

 1 #include<iostream>
 2 #include<fstream>
 3 using namespace std;
 4 class employee {
 5 private:
 6     int num;
 7     char name[20];  
 8     int age;
 9 public:
10     void  input(int num1, char * name1, int age1) {
11         strcpy_s(name, name1);
12         num = num1;
13         age = age1;
14     }
15     void show() {
16         cout << num << ends<<name<<ends<<age<<endl;
17     }
18 };
19 int main() {
20     employee e1, e2;
21     ofstream os("class.dat",ios::app|ios::binary|ios::out);//输出流
22     e1.input(12345, (char*)"小明", 19);
23     os.write((char*)(&e1) ,sizeof(e1));
24     os.close();
25 
26     ifstream is("class.dat", ios::binary | ios::in);//输入流
27     is.read((char*)(&e2), sizeof(e2));
28     e2.show();
29     is.close();
30 }

 

posted @ 2018-12-05 14:42  粥里有勺糖  阅读(414)  评论(0编辑  收藏  举报