Solutions for those exercises.
Questions
-
What is the name of the class we use to read from files?
-
FileReader
-
StreamOpener
-
ReadFile
-
StreamReader
-
FileStream
-
-
What is of crucial importance?
- Always call the
Open
method before reading from or writing into a file. - Always assume the user has
C:\
as their main drive. - Always call the
Close
method after being done reading from or writing into a file. - Never read from or write into a file inside a
try…catch
block.
- Always call the
Problems
-
Write a program that create a text file called
HelloWorld.txt
in itsbin/Debug
folder and store “Hello” followed by a name entered by the user in it. -
Write a program that ask the user for a filename, makes sure the filename ends with “.txt” and does not begin with a ”.” (otherwise, the file would be hidden on unix systems), does not match a file with the same name in the
bin/Debug
folder of your program, then create it in thebin/Debug
folder of your program and write in it all the number from 1 to 1,000,000 (both included). Out of curiosity, what is the file size? -
Execute the following program, then write a program that find the greatest number in the
RandomNumber.txt
file. -
Suppose that at
filePath
is located a file where each line is either- a decimal (e.g., 12.4, -14, 0.34),
- the word “STOP”,
- some other string (“Test”, “The sky is blue”, “Ignore this line”, “My file contains”), that may contain the characters “STOP”.
Write a program that displays the average of the decimals in the file knowing that
- your program should ignore the values after a line containing “STOP” and only “STOP” if it is present,
- all the other strings should simply be ignored.
For example, for the following three files, “4.0”, “10.0” and “7.5” should be displayed, as (12.48 - 2.48 + 2) / 3 = 4 (13 been ignored), (15 + 5) / 2 = 10, and (11 + 4) / 2 = 7.5 (12 being ignored).
-
Write a program that asks the user to enter a sentence, and store it in a file where the maximum width is 40: if the string entered is more than 40 characters long, then it should span over multiple lines of no more than 40 characters each. For example, if the user enters
then the text file should contain
-
Write a program that counts the number of words in itself! Ideally, empty lines should not count toward the word count.
Hint:
Program.cs
is normally located at