19.04.2017 Views

Learn to Program with Small Basic

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Let’s experiment <strong>with</strong> the first possibility <strong>to</strong> see what happens.<br />

Path Doesn’t Exist<br />

Run the short program in Listing 19-4.<br />

1 ' BadPath.sb<br />

2 path = "C:\Temp\Folder1\Out.txt"<br />

3 res = File.WriteContents(path, "Hello")<br />

4 TextWindow.WriteLine(res + ": " + File.LastError)<br />

Listing 19-4: Writing <strong>to</strong> a file when the path doesn’t exist<br />

You should see this output:<br />

FAILED: Could not find a part of the path 'C:\Temp\Folder1\Out.txt'.<br />

The program attempts <strong>to</strong> write the string "Hello" <strong>to</strong> an output file<br />

(lines 2–3). The direc<strong>to</strong>ry Temp exists, but the subdirec<strong>to</strong>ry Folder1 doesn’t<br />

exist, so WriteContents() fails.<br />

Appending <strong>to</strong> a File<br />

The AppendContents() method opens the specified file and adds data <strong>to</strong> the<br />

end of the file <strong>with</strong>out erasing its original contents. AppendContents() takes<br />

two arguments: the pathname of the output file and the string you want<br />

<strong>to</strong> append <strong>to</strong> the end of the file. If the operation is successful, the method<br />

returns "SUCCESS"; otherwise, it returns "FAILED". If the file you pass <strong>to</strong><br />

AppendContents() doesn’t exist, it’s created for you, and the string is written<br />

<strong>to</strong> it. If the file already exists, the string is appended <strong>to</strong> its end.<br />

To see the AppendContents() method in use, let’s say you need <strong>to</strong> maintain<br />

a log file that records actions, errors, and other events in your program.<br />

To keep the program simple, let’s just record the times when your<br />

program is executed. Every time your program runs, you add a record <strong>to</strong><br />

a log file that includes the date and time. The complete program is shown<br />

in Listing 19-5.<br />

1 ' AppendContentsDemo.sb<br />

2 outFile = <strong>Program</strong>.Direc<strong>to</strong>ry + "\Log.txt"<br />

3<br />

4 strLog = Clock.WeekDay + ", " + Clock.Date + ", " + Clock.Time<br />

5 result = File.AppendContents(outFile, strLog)<br />

6 If (result = "FAILED") Then<br />

7 TextWindow.WriteLine("Failed <strong>to</strong> write <strong>to</strong>: " + outFile)<br />

8 TextWindow.WriteLine(File.LastError)<br />

9 EndIf<br />

10<br />

11 TextWindow.WriteLine("Thank you for using this program. And for using <br />

deodorant.")<br />

Listing 19-5: Demonstrating the AppendContents() method<br />

Receiving File Input and Output 295

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!