I use this little program to understand how ftell works. I created a txt file and i typed in "15" and below that, in a second line, "no". So what I expected was it to print 0, then after it reads 15, print 2 and then since no is on the second line, meaning I have left a few "available spots" on the first line which i could have filled with more characters i would expect it to print definitely bigger number than 7 (which is what it actually printed). WHY?
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int x;
char box[10];
fp = fopen("test.txt", "r");
printf("%ld", ftell(fp));
fscanf(fp,"%d",&x );
printf("\n%ld", ftell(fp));
fscanf(fp, "%s", box);
printf("\n%ld\n", ftell(fp));
}
output: 0 2 7
There are nothing like available slots in a text file(*). It is just a mere sequence of characters, some of then being interpreted as an End Of Line (commonly
\r,\nor\r\n). So your text file should contain the following characters (assuming DOS/Windows EOL):This one should give for output: 0 2 6.
If you have 7 as the last value, you have probably a space somewhere, probably at the end of the first line (between
5and\r).At least on common OS, text files are represented as streams with line delimiters. Thanks to @JohnBollinger for noticing that other OS could have featured fixed lenght records text files