The black part is the program, the white part is the annotation, and part of the content is reproduced in the sub-network.
1. Header file
#include <cstdio>
#include <unistd.h>
2. Open the file
typedef struct { unsigned char head[2]; unsigned char status; unsigned char crc8; unsigned short datalen; }BACKUP_HEAD;
BACKUP_HEAD bhead = {
'A'
,
'B'
,
0x0A
,
0x0A
,
0x0A
};
FILE *fp = (FILE *)0x00; if(!(fp = fopen("/dev/mtdblock4", "w+"))) return -0x01;
w is to open the file in text mode, wb is to open the file in binary mode, when opening the file in text mode, every time the fwrite function encounters a 0x0A,
Just add 0x0D in front of it. Do not add other content.
Such as:
fwrite((char *)&bhead,sizeof(BACKUP_HEAD),1,fp);Our structure defines three 0x0A, so when operating with a text file, the content of 0x0A will not be written, but it is equivalent to carriage return and line feed.
result:
Replace w with wb+
FILE *fp = (FILE *)0x00; if(!(fp = fopen("/dev/mtdblock4", "wb+"))) return -0x01;rewrite
fwrite((char *)&bhead,sizeof(BACKUP_HEAD),1,fp); the result is
The binary mode will output the data to the file as it is stored in the memory.
Summarize:
(1) Write and read should be consistent. If writing is in text mode, it should be in text mode when reading; if writing in binary mode, it should be in binary mode when reading.
(2) Whether it is a text file or a binary file, if the binary method is used for reading and writing, there will be no error.