fwrite & fread 的使用
Posted eternalmoonbeam
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了fwrite & fread 的使用相关的知识,希望对你有一定的参考价值。
每一次切换文件操作模式必须调用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 的使用的主要内容,如果未能解决你的问题,请参考以下文章
对 STL 字符串使用 fread/fwrite。这是正确的吗?
如何使用 fread 和 fwrite 函数读写二进制文件?