SEQUENTIAL FILE WRITING

Generally, the syntax computer languages use for writing text data to files is similar to that used for writing to the screen or printer. The language regards the screen or printer as just another place to send a stream of characters. This makes it easy to test your program with writing to the screen and then switch to writing to a file. You still have to open the file and use a special variable to refer to it as shown in the following pseudocode:

OPEN "theoutput.txt" AS #out
PRINT #out "Hello World"
CLOSE #out

In most languages, opening a file with an existing filename can cause the previous contents to be overwritten; however, there is usually a syntax for opening a file in the append mode so that new data is written at the end of the file.

You have to be careful about the conventions each particular programming language has with respect to writing complete text lines. In other words, you need to understand whether or not the language automatically writes a line terminator character sequence with every PRINT statement.

For example, if you're writing a file of addresses and want to put the entire address on one line, you don't have to write a single PRINT command to do the whole thing. But you do have to be careful when choosing the syntax for the particular language you're using. For example, in Java, the following three lines of code write a single line of text to a file named out because only the println command automatically adds a line terminator.

out.print( lastName + ", " + firstName + " - " );
out.print( streetAdr + ", " + city + " - " );
out.println( phoneNumber );

Writing and Reading Whole Objects

Some object-oriented languages, such as Java and C#, provide convenience methods that enable you to write the entire contents of a complex object to a file. Later you can read the object back in and resume working with it. This capability can be extremely handy.

For example, suppose you are writing a program that has a number of personal preference settings for each user. You want to be able to read the settings when the user starts the program and then save them whenever the user changes them.

Assuming you have designed your program so that all user settings are contained in a single object named userPref , the pseudocode for saving that object in a file named userWB.dat is as simple as the following:

OPEN "userWB.dat" FOR OBJECT WRITING AS #obj
WRITE #obj userPref
CLOSE #obj

The real code in Java or C# would be a little longer because you would have to take into account the various errors that could happen, but it would still be quite simple.

When reading and writing objects, you can't change the definition of what goes in the object and still be able to use objects saved with the old definition.