3

In the standard C library, we can treat a file as binary or text, by fopen() with or without b type argument.

In Linux/POSIX API, can we treat a file as binary or text, by some way? Does open() not provide similar type argument?

  • 2
    In [Linux/]POSIX API, text mode and binary mode are equal: there is no difference between modes `"r"` and `"rb"` (or `r+` and `rb+`, ...) https://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html – pmg May 27 '19 at 18:21
  • There is no need for `O_BINARY` with [`open()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html) in the POSIX environment, though it may be available under Windows. However, you can use `#ifndef O_BINARY` / `#define O_BINARY 0` / `#endif` if you really want to. Then you can write `int fd = open(name, O_RDONLY | O_BINARY);` for both POSIX and Windows. The nuisance is that you have to ensure that the surrogate value for `O_BINARY` is defined — you should probably put the information into a header that's used where you use `open()`. – Jonathan Leffler May 27 '19 at 19:25
  • 1
    C provides binary and text modes so that it can support systems in which text files contain different actual bytes in the file (such as a two-character combination of new-line and carriage-return) than appear in the C stream presentation (a single new-line character). In binary mode, the I/O routines give you the actual bytes in the file. In text mode, the I/O routines convert between the actual bytes and what you see in C for text files. In POSIX, the actual bytes are the same as the appearance, so binary mode and text mode would functional identically—there would be no changing of bytes. – Eric Postpischil May 27 '19 at 20:14
  • 1
    So there is no need for a native text mode in POSIX. However, if you are, say, trying to read a Windows file on a POSIX system, then you need to translate the Windows bytes to POSIX bytes. For line endings, this may simply be discarding the carriage returns (depending on what processing you need to do). – Eric Postpischil May 27 '19 at 20:15
  • @JonathanLeffler where does it say that `open()` can have argument O_BINARY or O_TEXT? I can't find it in the link you gave. –  May 27 '19 at 21:29
  • 1
    @Ben:There's nothing about `O_BINARY` or `O_TEXT` in POSIX; the concepts are irrelevant. However, I believe I've seen in times past code intended for Windows which used `open()` with at least `O_BINARY` (I'm not sure whether I've seen `O_TEXT`, but it makes sense). I'm simply observing that such code can be made to work on POSIX systems by defining `O_BINARY` as `0` (and `O_TEXT` as `0` too) — and no harm is done (except nominally treading on namespace reserved for the implementation). – Jonathan Leffler May 28 '19 at 01:50

0 Answers0