Reputation: 13
Why the content of the ptr_01
is printed as NULL when I used (1). But the same is printed as the remaining string (content of the file after 1 fscanf()
). Why?
I still don't get how does fscanf works?
When I used (3) 2nd string of the file prints and the pointer shifts again by 1 string. I mean, (4) then prints the rest of the content. But if ptr_01
has the content of the file as it is printed using (2) & (4) why it is printing NULL with (1) ?
#include <stdio.h>
int main()
{
FILE *ptr_01;
char string_01[200];
ptr_01 = fopen("myread.txt", "r");
printf("%s ", *ptr_01); // Why this prints as NULL?? --------(1)
fscanf(ptr_01, "%s", string_01);
printf("%s", *ptr_01); // While this prints as the rest of the content of the file. ---------(2)
fscanf(ptr_01, "%s", string_01); -----(3)
printf("%s", *ptr_01); ---(4)
fclose(ptr_01);
return 0;
}
Upvotes: 0
Views: 197
Reputation: 123458
A FILE *
like ptr_01
points to an object that stores information about a stream (text or binary, input or output or append, wide or narrow character, current position, any error state) - it does not point to a specific position within the file.
You are not meant to dereference or manipulate ptr_01
directly - you just pass it as an argument to the various stdio
routines to read from or write to the stream, or to test for end of file and other conditions.
Upvotes: 1
Reputation: 11377
The return value of fopen is not a string containing the content of the file. You need to use one of the file-reading functions for that, like getc or fgets.
Example:
ptr_01 = fopen("myread.txt", "r");
if (ptr_01 != NULL) {
fgets(string_01, sizeof string_01, ptr_01);
...
}
Upvotes: 2