
C Programming, Exercises for the third week
1. What is the output of the following program?
#include <stdio.h>
int main( int argc, char *argv [ ])
{
int ch;
FILE *fptr;
fptr = fopen( argv[ 1 ], "r");
while ((ch = getc( fptr )) != EOF)
if (ch == ’ ’ || ch == ’\t’)
putchar (’\n’);
else
putchar (ch);
fclose (fptr);
return 0;
}
2. Modify Example 3 of the third week to append user input to an existing text
file. So your program reads a user input (character string) from the keyboard
and appends the string to a text file.
3. Write a program that removes all empty lines (i.e. lines containing only the-
end-of-line character) from a text file. (Hint: It is easiest just to copy the text
file to another text file leaving the empty lines away. Notice the Windows
environment, too, i.e. \r\n.)
4. Write a program that counts the number of characters and words in a text file.
Use the command-line arguments to read the name of the file from a keyboard.
5. Write a program that reads character strings from a text file (strings are se-
parated with ’#’ from each other) into two dimensional array and rearranges
them into alphabetical order, and then displays the rearranged list.
(Hint: It is possible to use the qsort sorting program, but this may be difficult,
because then you must use pointers in an tricky way. If you implement a sorting
algorithm yourself, for example bubble sort, then instead of an ordinary two
dimensional array it is better to use a one dimensional array whose elements
are pointers to strings. In this case you just swap pointers, it is not necessary
to copy strings. )
6. (The exercises from this onwards form a larger program.)
Create a function called is_line_break that takes a char value as input, and
outputs a c-like boolean value as output (1 for true, 0 for false). The value for
the output is defined by the given char value: if the value is ’\n’ or ’\r’ (line
change indicators), return 1, otherwise return 0.
1