Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how C output LF to stdout without being changed to CR LF?

On Windows this

#include <stdio.h>

int main() { 
    putc('A',stdout);
    putc('\r',stdout); 
    putc('\n',stdout);
}

outputs

A<CR><CR><LF>

How to write just LF char to stdout without automatic conversion to CR LF?

I need it to make simple socket stream reader to stdout. I've tried bcc32 from CodeGear, mingw, tinycc all yield same result, changing putc to putchar, fputc, fwrite doesn't help either.

like image 546
Daniel Leung Avatar asked Apr 28 '11 03:04

Daniel Leung


2 Answers

The MSVC solution is:

#include <io.h>
#include <fcntl.h>
...
_setmode(1,_O_BINARY)

Other runtimes may provide the C99 solution or an alternate way. EDIT: I believe setmode([file number],O_BINARY) originated on Borland Turbo C, and other compilers for MS-DOS and Windows imitated it. The _ prefix is done to keep the namespace clean, and may not be present on some compilers.

like image 157
Random832 Avatar answered Nov 10 '22 18:11

Random832


A text file converts the C character '\n' into the native line ending on output, and converts the native line ending on input into a single '\n'.

To get the result you require, you'd have to change stdout into a binary file stream.

A partial answer is found here. If you have a C99-compliant library, using:

if (freopen(0, "wb", stdout) == 0)
    ...oops...operation failed...

will attempt to change standard output to a binary stream. However, on Windows, the 'C99-compliant library' might be a problem. Nominally, this is the portable (because standard) answer. There is likely a Windows-specific function to do the same job.

like image 34
Jonathan Leffler Avatar answered Nov 10 '22 17:11

Jonathan Leffler