Every file operation mode switch must call fclose to close the file.
If the direct switching operation mode , file corruption (garbled) or operation fails.
When calling the fclose, be recovered as a file pointer parameters must be defined again, it is preferable functional package.
When the memory array, fwrite size_t size parameter can be used sizeof (buffer [0]), size_t count may be used sizeof (buffer) / sizeof (buffer [0]).
fread returns an integer, which is the number of successfully read the data, which is the maximum value of the parameter size_t count.
When using sequential read cycle while (! Feof (stream)), fread trigger-file condition after an incomplete reading.
one example:
#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; }