I am trying to fully grasp how these functions work.
From the Reference50 website:
fseek
FILE* out = fopen("out.txt", "w+");
fputs("Team Bowden Fever!", out);
char buffer[50];
fseek(out, 0, SEEK_SET);
fgets(buffer, 50, out);
printf("%s\n", buffer);
fclose(out);
fgets:
FILE* fp = fopen("example.txt", "r");
if (fp == NULL)
{
printf("File does not exist.\n");
return 1;
}
char s[2]; //wanted to try out what happens if I change the value from 50 to 2.
while(fgets(s, 2, fp) != NULL)
{
printf("%s", s);
}
fclose(fp);
fseek
In the first snippet of code a string of text is outputted to out.txt. Then an array of 50 chars is defined to contain the string. fgets then reads in, at most, 50 characters from file out.txt, storing them temporarily in buffer buffer which is then printed out to the screen by means of the printf function.
- What does fseek do in this case?
There's an offest of 0 bytes and SEEK_SET changes the location of the pointer out to the beginning of the file.
Why does nothing get printed out if I omit the fseek function or even change SEEK_SET to SEEK_CUR or to SEEK_END?
What's the current position of the file pointer before fseek?
fgets
Assuming there's a file called example.txt in my directory which contains the string: hello world!
- why does it still get printed out integrally even though I changed the numbers of characters to be read from the file? (from 50 to 2 i.e.)