Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C's "fopen" take a "const char *" as its second argument?

Tags:

c

file-io

history

It has always struck me as strange that the C function "fopen" takes a "const char *" as the second argument. I would think it would be easier to both read your code and implement the library's code if there were bit masks defined in stdio.h, like "IO_READ" and such, so you could do things like:

FILE* myFile = fopen("file.txt", IO_READ | IO_WRITE);

Is there a programmatic reason for the way it actually is, or is it just historic? (i.e. "That's just the way it is.")

like image 880
Chris Cooper Avatar asked Mar 25 '10 20:03

Chris Cooper


1 Answers

I believe that one of the advantages of the character string instead of a simple bit-mask is that it allows for platform-specific extensions which are not bit-settings. Purely hypothetically:

FILE *fp = fopen("/dev/something-weird", "r+,bs=4096");

For this gizmo, the open() call needs to be told the block size, and different calls can use radically different sizes, etc. Granted, I/O has been organized pretty well now (such was not the case originally — devices were enormously diverse and the access mechanisms far from unified), so it seldom seems to be necessary. But the string-valued open mode argument allows for that extensibility far better.

On IBM's mainframe MVS o/s, the fopen() function does indeed take extra arguments along the general lines described here — as noted by Andrew Henle (thank you!). The manual page includes the example call (slightly reformatted):

FILE *fp = fopen("myfile2.dat", "rb+, lrecl=80, blksize=240, recfm=fb, type=record"); 

The underlying open() has to be augmented by the ioctl() (I/O control) call or fcntl() (file control) or functions hiding them to achieve similar effects.

like image 54
Jonathan Leffler Avatar answered Oct 11 '22 14:10

Jonathan Leffler