In the win environment, there are many methods to read and write files, such as the CFile class in MFC and some open-source projects such as QFile in QT. The open-source solution is good for multiple platforms, while MFC is only Microsoft's own stuff. It is best not to use MFC for people who want to write cross-platform data.
When I was writing and developing recently, I suddenly encountered a problem, which is also related to reading and writing files. However, I used the C method instead of the C ++ method, the problem is that all files created with Open in C are read-only. Normally, this method is rarely found on the Internet, and the function still has a permission parameter. The default value is read-only. Now we will summarize the two file operations in method C.
Open is a lower-level IO operation than fopen, so the program requires more manual operations.
Int open (const char * path, int access, int mode)
Path: the path and name of the file to be opened
The access mode. The macro definition and meaning are as follows:
O_RDONLY 1 read-only open
O_WRONLY 2 Write-only open
O_RDWR 4 read/write Enabled
You can also select the following modes and the above three basic modes:
O_CREAT 0x0100 create a file and open it
O_TRUNC 0x0200 open an existing file and set the file length to 0.
O_EXCL 0x0400 not used
O_APPEND 0x0800 append the file to open
O_TEXT 0x4000 Open Text File translation CR-LF control characters
O_BINARY 0x8000 enable binary without CR-LF Translation
Mode: this parameter is only used in access = O_CREAT mode. Its values are as follows:
S_IFMT 0xF000 file type mask
S_IFDIR 0x4000 directory
S_IFIFO 0x1000 FIFO dedicated
S_IFCHR 0x2000 characters dedicated
S_IFBLK 0x3000 dedicated
S_IFREG 0x8000 only 0x0000
S_IREAD 0x0100 readable
S_IWRITE 0x0080 writable
S_IEXEC 0x0040 executable
FILE * fopen (char * filename, char * mode)
Filename file name
Mode open mode:
R: open a text file in read-only mode
Open a binary file in rb read-only mode
W. Open a text file in write-only mode
Wb only opens a binary file in write mode
A. Open a text file by append
Open a binary file through AB append
R + readable and writable mode to open a text file
Rb + readable/writable mode to open a binary file
W + readable and writable mode to create a text file
Wb + readable and writable to generate a binary file
A + readable and writable append method opens a text file
Append a binary file in the AB + readable/writable mode.
Differences between open and fopen:
The former is a low-level IO, and the latter is a high-level IO.
The former returns a file descriptor, and the latter returns a file pointer.
The former has no buffer, and the latter has a buffer.
The former works with read and write, and the latter works with fread and fwrite.
The latter is expanded based on the former. In most cases, the latter is used.