C Programming - Input / Output - Discussion

Discussion Forum : Input / Output - Find Output of Program (Q.No. 4)
4.
If the file 'source.txt' contains a line "Be my friend" which of the following will be the output of below program?
#include<stdio.h>

int main()
{
    FILE *fs, *ft;
    char c[10];
    fs = fopen("source.txt", "r");
    c[0] = getc(fs);
    fseek(fs, 0, SEEK_END);
    fseek(fs, -3L, SEEK_CUR);
    fgets(c, 5, fs);
    puts(c);
    return 0;
}
friend
frien
end
Error in fseek();
Answer: Option
Explanation:

The file source.txt contains "Be my friend".

fseek(fs, 0, SEEK_END); moves the file pointer to the end of the file.

fseek(fs, -3L, SEEK_CUR); moves the file pointer backward by 3 characters.

fgets(c, 5, fs); read the file from the current position of the file pointer.

Hence, it contains the last 3 characters of "Be my friend".

Therefore, it prints "end".

Discussion:
14 comments Page 2 of 2.

Bhavin said:   1 decade ago
What is the meaning of -3L here?? How it is different from normal -3?

Abc said:   1 decade ago
What is c[0]=getc(fs); for?

Krishan said:   1 decade ago
fseek moves the file pointer to the desired position. the last character in the file being EOF, fseek(fs, 0, SEEK_END) moves the poointer to EOF position. now it moves back to 3 characters again to the left that is to 'e' ....
f r i e n d EOF. so, now it prints from current position i.e. end

Cheran said:   1 decade ago
Can some explain this very Clear. I am confused how it went to 'end'.


Post your comments here:

Your comments will be displayed after verification.