how to make getc() on stdin be binary

488 views Asked by At

I'm using a while loop with getc() to read from a file handle and it works fine. Now I'm adding support for pipes.

My problem is that while x0A, X0D, and x0A0D pass just fine, any cases of x0D0A get reduced to just x0A. Also x1A seems to stop the process entirely when encountered.

I'm piping in the output of tar, and is messing the files up.

FILE *FH;
FH=stdin; 
int buff;
while((buff=getc(FH))!=EOF) {
    //stuff
}

That's simplified, as FH needs to point to either a file or stdin. For testing I'm just writing the buff out to a file to see the changes. The code works perfectly if FH is a file.

I've seen the same behavior on using tar, type, and cat as the pipe source

2

There are 2 answers

14
Mats Petersson On BEST ANSWER

You will need to fopen with a binary mode. I'm not sure if you can use freopen on stdin, but give it a try:

freopen(NULL, "rb", stdin);
3
this On

You have to open the file in binary mode you are writing into. The combination 0d0a is a carriage return followed by new line and depending on the system will get changed when you write in text mode.