C++中的文件寫入和讀取(文本文件方式,二進制方式)


一、文件的寫入

1 // 寫文件操作  文本文件寫入
2 ofstream ofs;
3 ofs.open("temp.txt",ios::out);
4 ofs << "姓名:張三" << endl;
5 ofs << "性別:男" << endl;
6 ofs << "學校:楚雄師范學院" << endl;
7 ofs.close();
//寫文件  二進制方式操作
class Person
{
public:
    char m_name[64];
    int m_age;
};
void main()
{
    ofstream ofs;
    ofs.open("Person.txt",ios::out | ios::binary);
    Person p = { "張三",18 };
    ofs.write((const char *)&p, sizeof(Person));
    ofs.close();

}

 

 

二、文件的讀取(5中方式)

1~4  文本文件讀取

5      二進制文件讀取

方式1:

1     //1.
2     ifstream ifs;
3     ifs.open("temp.txt", ios::in);
4     char buf1[1024] = { 0 };
5     while (ifs >> buf1)
6     {
7         cout << buf1 << endl;
8     }
9     ifs.close();

方式2:

1       2. 
2     ifstream ifs;
3     ifs.open("temp.txt",ios::in);
4     char buf2[1024] = { 1 };
5     while (ifs.getline(buf2,sizeof(buf2)))
6     {
7         cout << buf2 << endl;
8     }
9     ifs.close();

方式3:

1     3.
2     ifstream ifs;
3     ifs.open("temp.txt",ios::in);
4     string str;
5     while (getline(ifs,str))
6     {
7         cout << str << endl;
8     }
9     ifs.close();

方式4(不推薦):

    //4.(不推薦)
    ifstream ifs;
    ifs.open("temp.txt",ios::in);
    if (! ifs.is_open())
    {
        return 0;
    }
    char ch;
    while (( ch = ifs.get())  != EOF)
    {
        cout << ch;
    }
    ifs.close();

 方式5:

    // 讀文件   二進制方式
    ifstream ifs;
    ifs.open("Person.txt",ios::in | ios::binary);
    if (! ifs.is_open())
    {
        return 0;
    }
    Person p2;
    ifs.read((char *)&p2, sizeof(Person));
    ifs.close();
    cout << p2.m_name << endl;
    cout << p2.m_age << endl;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM