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

前端 未结 3 704
后悔当初
后悔当初 2020-12-11 05:15

On Windows this

#include 

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

outp

相关标签:
3条回答
  • 2020-12-11 05:46

    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.

    0 讨论(0)
  • 2020-12-11 05:52

    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.

    0 讨论(0)
  • 2020-12-11 06:00
    #ifdef _WIN32
    #include <fcntl.h>
    #include <io.h>
    #endif
    
    #ifdef __BORLANDC__
    #define _setmode setmode
    #endif
    
    #include <stdio.h>
    
    static void binary_stdout(void) {
    #ifdef _WIN32
        _setmode(_fileno(stdout), _O_BINARY);
    #endif
    }
    
    int main(void) {
        binary_stdout();
        printf("\n");
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题