Platform : Windows
Language : C
I have two programs:
- Program 1 reads
.jpg
file in binarymode(_setmode(_fileno(stdin), _O_BINARY) ,_setmode(_fileno(stdout), _O_BINARY)
using fread and outputs the using fwrite to stdout. - Program 2 reads from stdout and outputs to a file(
read/write
done in binary mode). But I can see that output image is corrupted and not same as input. I executedprogram1.exe | program2.exe
in powershell.
But if I write a program to read a file in binary mode and write it to another file in binary mode, then outputs are same. Problem occurs only when I use stdin
and stdout
.
Program 1:
int main()
{
int mode, fd, ret;
errno_t err;
int a = _setmode(_fileno(stdin), _O_BINARY);
a = _setmode(_fileno(stdout), _O_BINARY);
//freopen("ooo", "wb", stdout);
//char in[4096];
char in[4096];
char o[100];
int size = sizeof(in);
FILE* fpIn, * fpOut, * fp3, * fin;
//int a =_setmode(_fileno(stdin), _O_BINARY);
int x = sizeof(in);
fpOut = fopen("out", "wb");
//int bb = _setmode(_fileno(fpOut), _O_BINARY);
fin = fopen("pic.jpg", "rb");
//fin = fopen("in.txt", "rb");
//a = _setmode(_fileno(fin), _O_BINARY);
//int length = fread(&in, sizeof(in), 1, stdin);
int count = 0;
while ((count = fread(in, 1, sizeof(in), fin)) != 0)
{
fwrite(in, 1, count, stdout);
fflush(stdout);
}
fclose(fpOut);
}
Program 2:
int main()
{
int a = _setmode(_fileno(stdin), _O_BINARY);
a = _setmode(_fileno(stdout), _O_BINARY);
//freopen("ooo.txt", "wb", stdin);
char in[4096];
int o[100];
int size = sizeof(in);
FILE* fpIn, * fpOut, *fp3,*fin;
//int a =_setmode(_fileno(stdin), _O_BINARY);
int x = sizeof(in);
fpOut = fopen("out", "wb");
//int bb = _setmode(_fileno(fpOut), _O_BINARY);
fin = fopen("pic.jpg", "rb");
a = _setmode(_fileno(fin), _O_BINARY);
//int length = fread(&in, sizeof(in), 1, stdin);
int count=0;
while ((count = fread(in, 1, sizeof(in), stdin)) != 0)
fwrite(in, 1, count, fpOut);
fclose(fpOut);
}
The requirement of program is to allow user to input arbitrary input through stdin and write it to a file.