Text Files

The first type of file that every programmer writes to and reads from is an ASCII text file . A text file is a kind of computer file that is structured as a sequence of lines. Each line is terminated with a special character such as a line feed (LF) in UNIX or a carriage return (CR) and line feed (LF) in MS DOS.

I have abstracted the details behind reading and writing files by encapsulating the logic into two classes for your use.

The write text file class has the following methods.

  • OpenDataFile() – Open a given file in write or append mode.
  • PushData() – Write a line of data to the given file.
  • CloseDataFile() – Close the given file.
  • RemoveFile() – Remove a given file.

The read text file class has the following properties and methods.

  • EOF – a property that reflects if we are at the end of file.
  • OpenDataFile() – Open a given file in read mode.
  • PullData() – Return a line of data if not EOF.
  • CloseDataFile() – Close the given file.
  • FileExists() – Does a given file exist?
  • PullAllData() – Return the contents of the file as one big string.

One special type of text file is called a Comma Seperated Value (CSV) file.  CSV is a delimited data format that has fields/columns separated by the comma character and records/rows terminated by newlines.  Fields that contain a special character (comma, newline, or double quote), must be enclosed in double quotes.

In real life practice, CSV files can be problematic if care is not given to scrub special characters from the data fields before writing to the file.

The write sample program creates a CSV file representing the first five US Presidents demographic information.  The read sample program prints the file information to the MS DOS screen.

In summary, writing to and reading from ASCII text files is very easy.  The supplied classes can be used to create files of many different formats such as Tab Delimited and Comma Seperated Values to name a few.

The table below has starter code that you can use in your next Visual Basic (VB) Script.

mod-read-text-file.vbs Read Text File Class
mod-write-text-file.vbs Write Text File Class
tst-read-text-file.vbs Read Sample Program
tst-write-text-file.vbs Write Sample Program
read.cmd Read Batch File
write.cmd Write Batch File
presidents.csv CSV Sample File







This is a screen shot of the read sample VB Script excuting in a MS DOS command shell.



Output from read text file program

Related posts

One Thought to “Text Files”

  1. I just added this feed to my bookmarks. I have to say, I very much enjoy reading your blogs. Keep it up!

Leave a Comment