The code below will printf out the no. of characters as 6, even if we enter only 2...

#include<stdio.h>
#include<string.h>
 
int main()
{
	FILE *fp;
	char c;

	
	fp=fopen("random","w");

	while((c=getchar())!=EOF)
		putc(c,fp);

	printf("\nNo. of characters = %ld",ftell(fp));
	fclose(fp);

}

ftell() returns the position of the file pointer within a file, not the number of characters in the file. Each time you hit the Enter key getchar() will read that key too and write it out to the file. MS-Windows operating system changes the '\n' (Enter key) to '\r' and '\n' (two keys instead of one).

Try typing characters without Enter key between them and the count will be different.

If you want to know how many characters are in the file just keep a counter to count them. Or you can re-read the file and then count them.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.