ccplusplus.com
Learn C, C++ Concepts
Friday, October 21, 2011
count number of characters in a file
/************************************************************* * File : count-number-characters-in-file.c * Author : Saurabh Gupta * Desc : Count the number of characters in a file * c program to count number of characters in a file * Source : http://saurabhgupta0527.blogspot.com/p/c.html * Created : AM 09:55 21 October 2011 ************************************************************/ #include <stdio.h> #include <stdlib.h> int main() { printf ("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"); printf ("XXXXXXXXXXXX counting characters in a file XXXXXXXXXXXX\n"); printf ("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"); printf ("\nUsage:\n\n"); printf ("to change the file change the variable value 'cfilename'\n\ with the name of file you want and recompile.\n\n"); int count = 0; /* number of characters seen */ FILE *fp; /* input file */ const char cfilename[] = "count-number-characters-in-file.c"; printf ("Processing file : %s\n\n", cfilename); /* character or EOF flag from input */ int ch; fp = fopen(cfilename, "r"); if (fp == NULL) { printf("Cannot open %s\n", cfilename); exit(8); } while (1) { ch = fgetc(fp); if (ch == EOF) break; ++count; } printf("Number of characters is : %d\n\n", count); fclose(fp); printf ("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"); return (0); } /* * OUTPUT * [sgupta@rhel54x54 c]$ gcc count-number-characters-in-file.c -o count-number-characters-in-file [sgupta@rhel54x54 c]$ ./count-number-characters-in-file XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXX counting characters in a file XXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX Usage: to change the file change the variable value 'cfilename' with the name of file you want and recompile. Processing file : count-number-characters-in-file.c Number of characters is : 2113 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX [sgupta@rhel54x54 c]$ */
See also
Other popular tricky C Sample Codes and language Concept
.
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment