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.

- 572
- 5
- 10
-
Has your program ever suffered a significant bottleneck caused by the parsing of the attribute string? – Kerrek SB Sep 25 '13 at 08:12
-
I would suspect the overhead of parsing that tiny string pales in comparison to the opening of the file itself. – goji Sep 25 '13 at 08:12
-
Valid points but the reasoning behind it is still unanswered. Aside from that, would you rather parse a mode string argument if you had created the function? I'm curious as to why. – Dylan Sep 25 '13 at 08:19
-
3@Dayalrai, `fopen(f, "wb")` is not more readable than something like `fopen(f, FILE_WRITE | FILE_BINARY)`, his question makes sense to me. – Michael M. Sep 25 '13 at 08:21
-
[A closely related question](http://stackoverflow.com/q/31433959/827263) asks why it doesn't use an `enum`; the answer is that `fopen` predates `enum`. The sample implementation of `fopen` in K&R1 (1978) only looks at the first character of the mode string, which could be `'r'`, `'w'`, or `'a'`. – Keith Thompson Jul 15 '15 at 17:29
2 Answers
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

- 119,891
- 44
- 235
- 294
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

- 4,259
- 3
- 19
- 32