File Word Counter - Problem
Write a program that counts the total number of words in a text file. Your solution must handle various error conditions gracefully:
- File not found: Return -1 if the file doesn't exist
- Permission errors: Return -2 if you don't have read permissions
- Empty files: Return 0 for empty files
- Valid files: Return the total word count
A word is defined as any sequence of non-whitespace characters separated by spaces, tabs, or newlines. For example, "Hello world!" contains 2 words.
Implementation Notes:
- Use appropriate try-catch blocks for error handling
- Consider different types of whitespace as word separators
- Handle edge cases like files with only whitespace
Input & Output
Example 1 — Valid File with Content
$
Input:
filename = "document.txt"
›
Output:
5
💡 Note:
File contains "Hello world from TutorialsPoint!" which has 5 words when split by whitespace
Example 2 — File Not Found
$
Input:
filename = "missing.txt"
›
Output:
-1
💡 Note:
File doesn't exist in the system, return -1 as specified
Example 3 — Empty File
$
Input:
filename = "empty.txt"
›
Output:
0
💡 Note:
File exists but contains no content or only whitespace, return 0
Constraints
- Filename length ≤ 255 characters
- File size ≤ 10 MB for practical purposes
- Handle UTF-8 encoded text files
- Must handle all common file system errors
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code