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;
}
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.
Kacper said:
1 decade ago
Segfault for me. C array has no null character, '\0'.
kacper@tower-mint ~/ctests $ cat io04.c
#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;
}
kacper@tower-mint ~/ctests $ gcc io04.c
kacper@tower-mint ~/ctests $ ./a.out
Segmentation fault
kacper@tower-mint ~/ctests $
kacper@tower-mint ~/ctests $ cat io04.c
#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;
}
kacper@tower-mint ~/ctests $ gcc io04.c
kacper@tower-mint ~/ctests $ ./a.out
Segmentation fault
kacper@tower-mint ~/ctests $
Gagandeep said:
10 years ago
c[0] = getc(fs);
puts(c);
What does these two commands do?
puts(c);
What does these two commands do?
Vijay chaudhari said:
10 years ago
int main()
{
int k=35;
printf("%d %d %d",k==35,k=50,k>40);
}
Can anyone gives me detail about this puzzle?
Answer is 0 50 0 but actual answer given is 0 50 1, How is this possible?
{
int k=35;
printf("%d %d %d",k==35,k=50,k>40);
}
Can anyone gives me detail about this puzzle?
Answer is 0 50 0 but actual answer given is 0 50 1, How is this possible?
CH.SURESH ROYAL said:
9 years ago
According to me, the answer is 0 50 0.
Note : order of evaluation from right to left.
i) k>40->FALSE ->0:
II) K=50 ->here once the K value changed to 50 : it prints K=50.
III) K==35-> Here K is 50 so 50==35-> FALSE->0
FINALLY OUT PUT : 0 50 0
Note : order of evaluation from right to left.
i) k>40->FALSE ->0:
II) K=50 ->here once the K value changed to 50 : it prints K=50.
III) K==35-> Here K is 50 so 50==35-> FALSE->0
FINALLY OUT PUT : 0 50 0
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers