File Character Count Assignment

For this assignment you will write a program that counts the number of times that a target character appears in a file. Write your entire program in the file file_char_count.c.

Command Line Arguments

Your program must work when run like this:

./file_char_count <filename> <target character>

For example, if you want to count the number of times 'e' appears in the file file.txt, you could run the program like this:

./file_char_count file.txt e

If the user uses the wrong number of command line arguments, print an error message and return with exit code 1. If argc[2] is more than 1 character long, print an error message and return with exit code 2.

char_count()

Write a function that reads the file and counts the occurrences of the target character. Use the following prototype:

int char_count(const char *filename, char target_char);

The first argument to the function is a string containing the name of the file to open. Your function must open the file with this name, look at each character in the file and compare it to target_char, counting up the number of times target_char is seen. This count is returned.

If fopen() returns NULL, there was a problem opening the file for reading, and your function must return -1.

You must write documentation for this function.

In main(), get the count using your function. If it returns -1, print an error message and return with exit code 3.

Example Output

The assignment came with a file named test.txt, with the following contents:

aaa
bbbbbb
c
yyyy
zzzzzzzz

So if you run the program like this:

./char_count test.txt y

you should see the following output:

4

Feel free to edit this file, write your own test files, or run the program on char_count.c itself.

Make sure you also run the program with a filename that does not exist, to be sure that errors are handled correctly.

Submission

Push your code to git-keeper. It will be automatically tested. You will also be graded on the following:

  • Proper style
  • Your program is organized as described above
  • Your char_count() function is properly documented