ccplusplus.com
Learn C, C++ Concepts
Friday, January 6, 2012
count number of line in file c
/******************************************************************* * File : count-characters-file.c * Author : Saurabh Gupta * Description : count number of line in file c * Date : PM 11:17 06 January 2012 * Source : http://www.ccplusplus.com/p/c.html * ToDo : try to remove gets *******************************************************************/ #include
void main() { FILE *fopen(), *fp; int c , nc, nlines; char filename[40] ; nlines = 0 ; nc = 0; printf("Enter file name: "); gets( filename ); fp = fopen( filename, "r" ); if ( fp == NULL ) { printf("Cannot open %s for reading \n", filename ); exit(1); /* terminate program */ } c = getc( fp ) ; while ( c != EOF ) { if ( c == '\n' ) nlines++ ; nc++ ; c = getc ( fp ); } fclose( fp ); if ( nc != 0 ) { printf("There are %d characters in %s \n", nc, filename ); printf("There are %d lines \n", nlines ); } else { printf("File: %s is empty \n", filename ); } } /* * * [sgupta@rhel6x64 file-handling]$ gcc count-characters-file.c -o count-characters-file [sgupta@rhel6x64 file-handling]$ ./count-characters-file Enter file name: ccplusplus.com There are 93 characters in ccplusplus.com There are 3 lines [sgupta@rhel6x64 file-handling]$ */
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment