I need some advice on how to reverse the contents of stdin. This is the part of my code which handles reversing stdin:
int reversestdin(FILE *file)
{
int a, b;
int lineas=0;
while ((a=fgetc(stdin)) !=EOF)
{
if (a=='\n')
lineas++;
}
for(b=0; b<lineas; b++)
{
rewind(stdin);
int d,len, e;
char str[2048], *ptr;
for(e=0; e<=b; e++)
{
fgets(str, 2048, stdin);
}
ptr=str;
for(d=0; d<2048; d++)
{
if(*ptr=='\n') break;
if(*ptr=='\0') break;
ptr++;
}
len=d;
ptr--;
for(d=len; d>0; d--)
{
printf("%c", *ptr--);
}
printf("\n");
}
return 0;
}
I also have a .txt file called example1 with the following contents:
LINE 1.1
LINE 1.2
LINE 1.4
This code works when I execute ./myprogram < example1.txt
. It outputs
1.1 ENIL
2.1 ENIL
4.1 ENIL
But, if I execute echo "This text should be reversed" | ./myprogram
it outputs:
(
That's it. An open bracket. I've discovered that if I omit the part of my code which counts lines and just manually say there is 1 line it works (for 1 line of course).
int reversestdin(FILE *file)
{
int a, b;
int lineas=1;
//while ((a=fgetc(stdin)) !=EOF)
//{
//if (a=='\n')
//lineas++;
//}
for(b=0; b<lineas; b++)
{
rewind(stdin);
int d,len, e;
char str[2048], *ptr;
for(e=0; e<=b; e++)
{
fgets(str, 2048, stdin);
}
ptr=str;
for(d=0; d<2048; d++)
{
if(*ptr=='\n') break;
if(*ptr=='\0') break;
ptr++;
}
len=d;
ptr--;
for(d=len; d>0; d--)
{
printf("%c", *ptr--);
}
printf("\n");
}
return 0;
}
It now outputs
desrever eb dluohs txet sihT