Mail Archives: djgpp/1995/11/02/12:18:03
On 2 Nov 1995, Justen Keven Marshall wrote:
> I am at my wits end trying to print a line-feed
> without a carriage return. (Or the other way around.)
> What happens is that when I try to print char(10) in
> a file, with printf redirected, fprintf, cout, putchar,
> fputchar, or whatever, it puts BOTH not just one.
And Eli Zaretskii responded:
DOS C compilers treat text and binary files differently. When writing to
a text file, a CR is produced for every LF, so that you could port
programs which print like this:
printf("Hello, world!\n");
and expect a CR-LF pair to be written, as required for DOS text files.
Any given file is treated as text or binary according to how it was
open. The default is TEXT, so that if you say `fp = fopen("file", "w")',
it is open as a text file. This is again for portability reasons,
because Unix programs don't know about the difference. To open a file in
binary mode, just add "b" to the flags you pass to fopen(), like this:
FILE *fp = fopen("file", "wb");
or use O_BINARY, if you do the same with open().
If you want to switch an already open file to binary mode (like for stdin
and stdout, which are open before your main() function runs), use the
setmode() library function, like this:
setmode(fileno(stdout), O_BINARY);
FYI - Both the binary flag ("wb"/"rb") to fopen() and the O_BINARY flag to
fopen and setmode() are ANSI 'C' compatible so all ANSI compilers, even on
UNIX, recognize these even when they ignore them. Using these, therefore, will
not impact code portability.
--
Art S. Kagel, kagel AT ts1 DOT bloomberg DOT com
Variety is the soul of pleasure. -- Aphra Behn
- Raw text -