This week, I've been working on a task, which is to write a model of multiple model training. We used the C language read and write method, engaged for a week, dug a lot of pits, eventually leveled. A number of useful knowledge are listed below.
The difference between 1.fwrite,fread VS fprintf,fscanf
Fwrite,fread Read and write, I found that regardless of the use of file* PFile = fopen ("Myfile.bin", "WB"), whether the use of "WB" or "W", the final written data are garbled, so the content is unreadable. But security is good, we later use Fwrite,fread to read and write model. and fprintf,fscanf is visible.
2. When using Fwrite,fread to read and write files, remember to note the format of variables, for example:
#include <stdio.h> #include <string.h> int Main () {FILE * pFile; PFile = fopen (, "WB" ); double a = 5.1615665161 ; Fwrite (&a, sizeof (float ), 1 , PFile); Rewind (PFile); PFile = fopen (, "RB" ); double b; Fread (&b, sizeof (float ), 1 , PFile); return 0 ;}
I read a double type of data, but want to write the file in float type, and then read it in float, and find that the read data B is wrong. The reason for this is that a double type, read into sizeof (float) bytes, is truncated, so the data is wrong. should read:
#include <stdio.h>#include <string.h>intMain () {FILE * pFile; PFile = fopen ("Myfile.bin","WB");DoubleA =5.1615665161;floatAtemp = A; Fwrite (&atemp,sizeof(float),1, pFile); Rewind (PFile); PFile = fopen ("Myfile.bin","RB");Doubleb;floatBtemp; Fread (&btemp,sizeof(float),1, pFile); b = btemp;return 0;}
That is, the original data must persist in the original format to read and write.
3. Multiple open files, the way to write data
Generally we use:
FILENULL"ab");
A that means additional meaning. Read, if we read some of the data first, then turn off the file, and then open the file, continue to read the next line of data, you can use
long offset = ftell(fp);
First note the pointer position offset of the previously read text, and then the next time you punch in the file, offset the file pointer from the offset.
*fp"rb"0);
Some experience of Fwrite,fread and FPRINTF,FSCANF