fwrite写入文件大小错误的问题

最近使用fwrite将缓冲区的内容写入文件,发现写入的字节数与预期的不一致,后来发现是打开文件时fopen使用的mode是“w”,改为“wb”问题解决。

查看BCB的帮助文档发现:

The mode string used in calls to fopen is one of the following values: 

Value Description

r

Open for reading only.

w

Create for writing. If a file by that name already exists, it will be overwritten.

a

Append; open for writing at end-of-file or create for writing if the file does not exist.

r+

Open an existing file for update (reading and writing).

w+

Create a new file for update (reading and writing). If a file by that name already exists, it will be overwritten.

a+

Open for append; open (or create if the file does not exist) for update at the end of the file. 


To specify that a given file is being opened or created in text mode append a t to the mode string (rt, w+t, and so on). Similarly to specify binary mode append ab to the mode string (wb, a+b, and so on).fopen also allows the t or b to be inserted between the letter and the+ character in the mode string; for example rt+ is equivalent tor+t.

If a t or b is not given in the mode string the mode is governed by the global variable_fmode. If _fmode is set to O_BINARY files are opened in binary mode. If_fmode is set to O_TEXT they are opened in text mode. TheseO_... constants are defined in fcntl.h.


原来BCB中fopen的“w”模式默认为“wt”,以文本方式打开文件。

二进制数据中难免有一些特殊字符,以文本方式打开后,fwrite每遇到一个0x0A就会在前面加一个0x0D,造成上面的问题。

Windows以“\r\n”为换行符

你可能感兴趣的:(C++)