Question 2: File I/O [8]
Write a function, named countChars, that takes a filename as a string parameter, opens the file, then counts and returns the number of characters in the file. It should return -1 if it was unable to open the file. The function should NOT contain any output statements.
Sample solution int countChars(string filename) { ifstream fpin; fpin.open(filename.c_str()); if (fpin.fail()) { return -1; } int count = 0; while (!fpin.eof()) { char c; fpin.get(c); if (!fpin.eof()) { count++; } } fpin.close(); return count; } |