11
$\begingroup$

In C, fopen() uses string literals such as "r" or "r+" or "w" to specify the mode with which to open a file. One possible reason for this I read is at the time C was so new that there might not have been a convenient way to create predefined constants.

However, the function fseek() which is part of the same file IO library uses predefined constants SEEK_SET SEEK_CUR and SEEK_END to specify the mode.

What was the motivation for using, at least what I consider a substandard approach for flag parameters for fopen() but not fseek()? If fseek() could use predefined constants as flags, why could fopen() not?

$\endgroup$
4
  • $\begingroup$ Where did you read this? Citation? $\endgroup$ Commented Apr 29 at 23:31
  • $\begingroup$ The natural way to use macro constants for fopen would have been with bitmasks, like Unix 'open' does. But I can't think of any place in the classic C standard library where bitmask constants are used, so maybe they wanted to avoid them for some reason. $\endgroup$ Commented Apr 29 at 23:36
  • 1
    $\begingroup$ I think, fseek() came later and probably the reason was that it used some file descriptor-based seek() syscall. But that is only hyphotese. Kerrigan could say, why has it so happened. $\endgroup$
    – peterh
    Commented Apr 29 at 23:44
  • 1
    $\begingroup$ Questions about the history of a language might be more appropriate for Retrocomputing. $\endgroup$
    – Barmar
    Commented Apr 30 at 20:54

1 Answer 1

6
$\begingroup$

I agree that this API choice of using strings instead of some form of more structured data is maybe not great. But your question is about why should we expect a difference between these designs?

For fseek there really are only a handful of possibilities and there are unlikely to be more. But for fopen, many implementations of this library method support additional options in that string parameter. For example, to open a UTF-8 text file:

FILE *fp = fopen("newfile.txt", "rt+, ccs=UTF-8");

Microsoft's implementation has dozens of extensions to the string argument; see https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/fopen-wfopen?view=msvc-170 for a list.

In short, it's an extension point for standard library implementations to take advantage of. Whether that was a motivation for the design, or a happy historical accident, I do not know.

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .