问题
Why is the 'mode' paramter for fopen
in C given by a string? It would make more sense (in my way of thinking) for it to be a bitmask or the likes. The overhead a string necessitates is inefficient and unnecessary.
回答1:
C11 §7.21.5.3 The fopen function
The argument
mode
points to a string. If the string is one of the following, the file is open in the indicated mode. Otherwise, the behavior is undefined.271)
In the footnote:
271) If the string begins with one of the above sequences, the implementation might choose to ignore the remaining characters, or it might use them to select different kinds of a file (some of which might not conform to the properties in 7.21.2
According to the C99 Rationale, the committee thinks an implementation may choose to use mode
other than the flags:
Rationale for International Standard — Programming Languages — C §7.19.5.3 The fopen function
An implementation may choose to allow additional file specifications as part of the mode string argument. For instance,
file1 = fopen(file1name, "wb,reclen=80");
might be a reasonable extension on a system that provides record-oriented binary files and allows a programmer to specify record length.
GNU libc has an extension that allows mode
contains ccs=STRING
, see glibc manual
回答2:
If it were a bitmask it would have been more limited to future expansion. The GNU C library already allows 10 different modes, and MSVC 15. Additionally they support the ,ccs=string
syntax which would not be possible with a bitmask
来源:https://stackoverflow.com/questions/18999459/c-fopen-mode-parameter