Read from stdin using read
سؤال
I'm using the following code to read from stdin
int size;
int bufferSize=2000;
char echoString[bufferSize];
while ((size = read(fileno(stdin), echoString, bufferSize)) > 0){
write(fileno(stdout), echoString, size);
}
To write the data got from stdin on the screen... but it just dont work well. If i do a cat "hugetarfile.tar.gz" | ./myprogram | tar -zvt it works, but on the end it "crashed" telling there are some trash. If i do cat "hugetarfile.tar.gz" | tar -zvt it works like a charm..
on the end of the tar you can see:
gzip: stdin: decompression OK, trailing garbage ignored tar: Child returned status 2 added the File *fin = freopen(nill, "rb", "stdin")
Someone can help me? xD
Just to tell... i'm creating the read to send trough socket, but in this case this war is easier to test.
المحلول
I completed your program in the simplest way to make it compile without warning with gcc -ansi -D_POSIX_C_SOURCE -Wall -W demonofnight.c
:
#include <unistd.h>
#include <stdio.h>
int main()
{
int size;
int const bufferSize=2000;
char echoString[bufferSize];
while ((size = read(fileno(stdin), echoString, bufferSize)) > 0){
write(fileno(stdout), echoString, size);
}
return 0;
}
and executed it with
cat bigFile | ./a.out | md5sum
for several big files. I got the same md5 than with md5sum bigFile
.
Conclusion: the error is in what you don't show us.
نصائح أخرى
You must test for errors in your read and write. Why don't you test your program like:
./myprogram < hugetarfile.tar.gz > output.tar.gz
and make sure that hugetarfile.tar.gz and output.tar.gz are the same.
Regards