#include #include #include #include #define FALSE 0 #define TRUE 1 // This program counts the number of characters, words, // and lines in a file. // // Warning: I think it works properly, but it isn't fully tested. void main(void) { fstream countfile; int characters; int words; int lines; char c; int inaword; char filename[80]; cout << "Filename: "; cin >> filename; countfile.open(filename, ios::in); if(countfile.fail()) { cout << "Error opening file\n"; cout << "\nHit any key to exit\n"; getch(); exit(-1); } // Initialize the count variables characters = 0; words = 0; lines = 0; inaword = 0; while(1) { countfile.get(c); if(countfile.eof()) { if(inaword) { words++; inaword == FALSE; } lines++; break; } characters++; switch(c) { case ' ': case '\t': if(inaword == TRUE) { words++; inaword == FALSE; } break; case '\n': if(inaword == TRUE) { words++; inaword == FALSE; } lines++; break; default: if(inaword == FALSE) inaword = TRUE; break; } } countfile.close(); cout << "Characters: " << characters << endl; cout << "Words: " << words << endl; cout << "Lines: " << lines << endl; cout << "\nHit any key to exit\n"; getch(); }