I've written a code which is supposed to take the input from the user, save it in a file called "name" and then print it in the reverse order. But its getting stuck in an infinite loop, printing only the last character typed. The logic of the program is that, the getc(fp) in putchar(getc(fp)) will return a character and advance the file pointer by 1. The putchar will print the character and the condition in the while loop will bring the cursor back 2 places so that the next charcter can be printed...
Code:
#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp;int n;
char c;
fp=fopen("name","w");
if(fp==NULL)
printf("\nUnable to open\n");
while((c=getchar())!=EOF)
putc(c,fp);
printf("\nNo. of characters = %ld\n",ftell(fp));
fclose(fp);
fp=fopen("name","r");
n=0l;
while(feof(fp)==0)
{
fseek(fp,n,0);
printf("Position of %c is %ld\n",getc(fp),ftell(fp));
n=n+5l;
}
putchar('\n');
n=ftell(fp);
fseek(fp,n-1,0);
do
{ putchar(getc(fp));
}while(!fseek(fp,-2L,1));
fclose(fp);
}