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
INPUTALGORITHMRESULTFilenamedocument.txtFile Content:Hello worldfromTutorialsPoint!(5 words total)1Try Block - Check File2Open & Read File3Count Words4Handle ExceptionsError Handling:FileNotFound → -1PermissionError → -2Empty File → 0Valid File → word countCharacter-by-character processingWord Count5Success! File contained5 words separated bywhitespace charactersKey Insight:Proper try-catch blocks handle all file errors gracefully while efficiently counting words character-by-characterTutorialsPoint - File Word Counter | Structured Error Handling
Asked in
Microsoft 35 Google 28 Amazon 22 Apple 18
23.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen