码迷,mamicode.com
首页 > 其他好文 > 详细

fwrite & fread 的使用

时间:2019-10-02 12:47:57      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:return   封装   hello   buffer   using   stream   ESS   https   col   

每一次切换文件操作模式必须调用fclose关闭文件。


 

如果直接切换操作模式,文件将损坏(出现乱码)或操作失败。


 

在调用了fclose时,作为参数的文件指针将被回收,必须再次定义,因此最好将功能封装。


 

存数组时,fwrite参数size_t size可使用sizeof(buffer[0]),size_t count可使用sizeof(buffer)/sizeof(buffer[0])。


 

fread返回了一个整数,是其成功读取的数据数目,最大值是其参数size_t count。


 

使用循环顺序读取时while(!feof(stream)),fread在一次读取不完整后触发文件尾条件。

一个例子:

#include<iostream>
#include<fstream>

int main()
{
    using std::cin;
    using std::cout;
    using std::endl;
    cout << "Hello, I am a C++ test program." << endl; 
    cin.get();
    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    
    FILE* _f0;
    _f0 = fopen("f0.txt", "wb");
    if (_f0 != NULL) 
    {
        cout << "I created a file named \"f0\"." << endl;
        cin.get();
        int buf[8];
        cout << "size of buf[0] = " << sizeof(buf[0]) << endl
            << "size of buf = " << sizeof(buf) << endl;

        for (int i = 0; i < 8; i++)
        {
            buf[i] = 0 + i;
        }
        fwrite(buf, sizeof(buf[0]), sizeof(buf)/sizeof(buf[0]), _f0);
        cout << "Then put some numbers into this file." << endl;
        cin.get();
        cout << "Read out these numbers:" << endl;
        fclose(_f0);
        FILE* _f1 = fopen("f0.txt", "rb");
        cout << "f0 = " << _f1 << endl;
        int i = 0;
        int R = 0;
        int n = 0;
        while (!feof(_f1))
        {
            n = fread(&R, sizeof(R), 1, _f1);
            cout << "n = " << n << " buf[" << i << "] = " << R << endl;
            i++;
        }
        fclose(_f1);
        cout << "At last, add a number to the file." << endl;
        FILE* _f2 = fopen("f0.txt", "ab");
        R = 8;
        fwrite(&R, sizeof(R), 1, _f2);
        fclose(_f2);
    }
    else 
    {
        cout << "File creating failed." << endl;
    }
    
    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    cout << endl << "Press enter to end.";
    cin.get();
    return 0;
}

 

fwrite & fread 的使用

标签:return   封装   hello   buffer   using   stream   ESS   https   col   

原文地址:https://www.cnblogs.com/eternalmoonbeam/p/11617114.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!