Click here to Skip to main content
15,895,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my following code I am demonstrating the fseek & the ftell functions.
Say I input ABCD and then the EOF !!
The output should be 4; instead it is showing 6.
Moreover the EOF is NOT being accepted in the same line(row) as ABCD, it is ONLY being accepted if I move to the next line(s).

For eg.
Say,
I input,
ABCDE
"EOF"
It should read the number of characters as 5. But it is reading it as 7.
5 + 1(for the next line) = 6
But the compiler is returning 7 as the result.

// Unable to Understand Why !!
// Also I would really appreciate if you could tell me why the EOF is not being accepted in the same line as the INPUT(in this case ABCDE).

******************************

C#
/* WAP that uses ftell & fseek */

#include<stdio.h>
#include<conio.h>

int main()
{
    FILE *fp;
    long n;
    char c;

    fp=fopen("RANDOM","w");

    while((c=getchar())!=EOF)
        putc(c,fp);

    printf("No of Characters Entered = %ld",ftell(fp));

    fclose(fp);

    fp=fopen("RANDOM","r");

    n=0L;

    while(feof(fp)==0)
    {
        fseek(fp,n,0);          /* Position to (n+1)th character */
        printf("\nPosition of %c is %ld",getc(fp),ftell(fp));
        n=n+5L;
    }

    putchar('\n');

    fseek(fp,-1L,2);            /* Position to the Last Character */

    do
    {
        putchar(getc(fp));
    }
    while(fseek(fp,-2L,1));

    fclose(fp);

return 0;
}
Posted

1 solution

If you press the ENTER key at the end of your string then the system will add \r\n (Carriage return and Line feed). And the EOF is always a separate line on input from the keyboard, as it is only recognised when entered on its own.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900