CS 140
Practice problems on Files
Here are some practice programming problems using files.
These are not to be handed in, though you should feel free to ask questions
about any of them outside of class. Remember that programming is an activity
that you learn by doing.
- Write a program that asks for a file name and then prints to the screen
the contents of the file with that name.
- Write a program that prints itself to the screen.
- Write a program that asks for a file name and then prints to the screen
the file with that name, only every instance of the word "bob" is
replaced by "The Most Noble and Supreme BOB". Here is an idea for
how to do this: each time you read a line, use the split( " ") function
of lines (which we used in the Concordance program) to split the line into
a list of words. If the word is not "bob", just print it, followed
by a space. If it is "bob" then instead print the substitute, followed
by a space.
- One of the debugging quesitons in HW5 asked you how to open a file and add
some text to the beginning. Do that. Write a program that opens up a file
(perhaps the program itself) and adds the line
# BOB RULES
to the top of the file.
- Write a program COPY that asks for the name of a file anthe name to give
a copy. The program then makes a copy of the orginal file under the new name.
Of course, the program shouldn't crash if the original file name doesn't match
an actual file.
- Write a program that reads a text file consisting of numbers, one number
per line, and computes the average of all of these numbers..
- Write a program that inputs a number N and then writes to a file "primes.txt"
all of the prime numbers between 2 andN.