32
Reading and Writing Files Keeping Data Keeping Data

Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

  • View
    214

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Reading and Writing FilesReading and Writing Files

Keeping DataKeeping Data

Page 2: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Why do we use files?

For permanently storing data.For permanently storing data.For dealing with information too For dealing with information too

large to fit in memory.large to fit in memory.

Page 3: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Sequential Access Files

Think of files as being stored on Think of files as being stored on tape.tape.

Sequential Access means you must Sequential Access means you must pass over all the information in a pass over all the information in a file to get the stuff you want.file to get the stuff you want.

Page 4: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Illustration

F1 F2 F4F3 File 5 F6 File 7

To get from here... To here...

We have to read all this.

Read Head

Tape Moves

Page 5: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Random Access Files

Think of files stored on a disk.Think of files stored on a disk.Random Access means you can Random Access means you can

have any information at any time. have any information at any time. (Like in RAM!)(Like in RAM!)

Page 6: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Illustration

File One

File Two

Move the head from one file to another ignoring everythingin between.

Page 7: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Random Access Files, Details

WE WILL NOT COVER THESE IN THIS WE WILL NOT COVER THESE IN THIS CLASSCLASS

These files use indexes to locate These files use indexes to locate information within them.information within them.

It means dealing with the indexes, how the It means dealing with the indexes, how the disk memory is used, special ways to delete disk memory is used, special ways to delete files …..files …..

Page 8: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Opening Files

Questions to Answer:Questions to Answer:Do you want to read from it, write to it, both?Do you want to read from it, write to it, both?Does the file already exist?Does the file already exist?What shall we do with the file that already What shall we do with the file that already

exists?exists?Are we looking at binary data or text data?Are we looking at binary data or text data?Where is the file?Where is the file?

Page 9: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

File Opening

A file must first be opened before it A file must first be opened before it can be used.can be used.

Opening a file does two things:Opening a file does two things:Makes sure its OK to open the fileMakes sure its OK to open the fileAssigns an identifier to the file.Assigns an identifier to the file.

Files stay open until we close them (or Files stay open until we close them (or the program ends)the program ends)

Page 10: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

OK to Open File?

You haven’t opened it alreadyYou haven’t opened it alreadyYou aren’t violating the file’s You aren’t violating the file’s

integrityintegritySomebody else has it open…Somebody else has it open…You’re already using for a different You’re already using for a different

purpose.purpose.

Page 11: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Assigning an Identifier

Allows us to identify which file to Allows us to identify which file to write to and read from.write to and read from.

Useful if Multiple Files are OpenUseful if Multiple Files are Open

Page 12: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

The Open Statement

Open file For Mode As filenumberOpen file For Mode As filenumberfile is the Full pathname of the file to file is the Full pathname of the file to

be opened.be opened.Mode is how the file will be used.Mode is how the file will be used.filenumber is the number that filenumber is the number that

identifies the file.identifies the file.

Page 13: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Modes

InputInputSequential access for reading, starts at beginningSequential access for reading, starts at beginning

OutputOutputSequential access for writing, erases old file and Sequential access for writing, erases old file and

starts at beginningstarts at beginningAppendAppendSequential access - doesn’t erase the file, starts Sequential access - doesn’t erase the file, starts

writing at the end.writing at the end.

Page 14: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Two Modes we Won’t Use

RandomRandomWhich we won’t use in this class - This Which we won’t use in this class - This

is the default!is the default!BinaryBinary

Which we also won’t use. Opens Which we also won’t use. Opens binary files.binary files.

Page 15: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

The Open Statement, Con’t

Opening a non-existent file for Input causes an Error!Opening a non-existent file for Input causes an Error! We’ll write a special function for handling this.We’ll write a special function for handling this. Opening a non-existent file for Output causes it to be Opening a non-existent file for Output causes it to be

created.created. Opening an existing file for Output causes it to be Opening an existing file for Output causes it to be

erased.erased. Opening an existing file for Append causes data to be Opening an existing file for Append causes data to be

entered at the end of the existing file.entered at the end of the existing file.

Page 16: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Output to a File

Write # filenum, variablelistWrite # filenum, variablelistfilenum is the file identifying number filenum is the file identifying number variable list is a list of variables. variable list is a list of variables.

This is the easiest file output function. This is the easiest file output function. Use it unless you are forced to use Use it unless you are forced to use

something else.something else.

Page 17: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Format

These are written out using commas These are written out using commas between values and double quotes between values and double quotes around strings.around strings.

““Here is a string”,19,27.3,”String”Here is a string”,19,27.3,”String”““More strings”,20,15.2,”More Text”More strings”,20,15.2,”More Text”

Page 18: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Illustration of File Writing

Dim fleeb As String, norb As SingleDim fleeb As String, norb As SingleDim ski As Integer, i As IntegerDim ski As Integer, i As Integerfleeb = “Test1”fleeb = “Test1”norb = 98.6norb = 98.6ski = 100ski = 100Open “file.txt” For Output As 1Open “file.txt” For Output As 1Write #1, fleeb, norb, skiWrite #1, fleeb, norb, skiClose 1Close 1

““Test1”,98.6,100Test1”,98.6,100

file.txtfile.txt

Page 19: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Printing to a File

Print # filenum, var ; var , var ; varPrint # filenum, var ; var , var ; varfilenumber is from the Open Statementfilenumber is from the Open Statementvar can be var can be

the function Spc(n), for n spaces,the function Spc(n), for n spaces,Tab(n) for nth column tab,Tab(n) for nth column tab,a variablea variable

the semicolon puts no space between itemsthe semicolon puts no space between itemsthe comma prints items with spaces.the comma prints items with spaces.

Page 20: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Input From a File

Input # filenumber, variablelistInput # filenumber, variablelistfilenumber is the file to read fromfilenumber is the file to read from

Identified in the open statement.Identified in the open statement.variables list is the list of variables to read the variables list is the list of variables to read the

value into.value into.numbers get numbers, strings get either double numbers get numbers, strings get either double

quoted strings or first word.quoted strings or first word.Use this if at all possible.Use this if at all possible.

Page 21: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Illustration of File Reading

Dim fleeb(1 To 3) As String, Dim fleeb(1 To 3) As String, Dim norb(1 To 3) As SingleDim norb(1 To 3) As SingleDim ski(1 To 3) As IntegerDim ski(1 To 3) As IntegerDim i As IntegerDim i As IntegerOpen “file.txt” For Input As 1Open “file.txt” For Input As 1For i = 1 to 3For i = 1 to 3 Input #1, fleeb(i), norb(i),ski(i)Input #1, fleeb(i), norb(i),ski(i)Next iNext iClose 1Close 1

““Test1”,98.6,100Test1”,98.6,100““Test 2”,93.1,100Test 2”,93.1,100““Quiz 3”,18,25Quiz 3”,18,25

file.txtfile.txt

fleebfleeb

norbnorb

skiski

Page 22: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Input From a File, Con’t

Input (n,filenumber)Input (n,filenumber)n is the number of characters to read in.n is the number of characters to read in.filenumber is the file to read from.filenumber is the file to read from.

This was identified in the Open statement.This was identified in the Open statement.

This is useful if you must read in a This is useful if you must read in a file created with the Print# function.file created with the Print# function.

Page 23: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Close File Statement

Close filenumber(s)Close filenumber(s)File identification number or numbers.File identification number or numbers.Closes file and removes number Closes file and removes number

assignment to it.assignment to it.Will “rewind” sequential files to Will “rewind” sequential files to

beginning.beginning.

Page 24: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

For i = 1 to 10For i = 1 to 10

Open “f” for Input As 1Open “f” for Input As 1

Input#, a(i), b(i)Input#, a(i), b(i)

Close 1Close 1

Next iNext i

Good ThingGood Thing Bad ThingBad Thing

Closing a File

Open “f” for Input As 1Open “f” for Input As 1

For i = 1 to 10For i = 1 to 10

Input#, a(i), b(i)Input#, a(i), b(i)

Next iNext i

Close 1Close 1

Page 25: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Formatting Data

Write Format must be the same as Write Format must be the same as Read Format to ensure that we Read Format to ensure that we have data integrity.have data integrity.

Be very careful of this.Be very careful of this.

Page 26: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

File Length

We don’t always know the file lengthWe don’t always know the file lengthWe can use the EOF(filenumber) function.We can use the EOF(filenumber) function.

filenumber is the number you assigned to the filenumber is the number you assigned to the file.file.

EOF returns True at the File end.EOF returns True at the File end.EOF returns False otherwise.EOF returns False otherwise.

Page 27: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Reading an unknown length file.

Open “file.txt” For Input As 1Open “file.txt” For Input As 1

While(Not EOF(1))While(Not EOF(1))

Input#1, fred, wilmaInput#1, fred, wilma

WendWend

Close 1Close 1

Page 28: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

FreeFile Function

A useful function when you’re A useful function when you’re opening a lot of files and you’re opening a lot of files and you’re not sure what number you want to not sure what number you want to assign to each.assign to each.

Identifies a number which has not Identifies a number which has not yet been assigned to a file.yet been assigned to a file.

Page 29: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Input Files that Don’t Exist

Requires us to use the error handling VB Requires us to use the error handling VB provides.provides.

We’ll put this in a function so that it We’ll put this in a function so that it doesn’t cause problems.doesn’t cause problems.

When an Error occurs in VB it looks for When an Error occurs in VB it looks for an error handler. If none is found, the an error handler. If none is found, the program ends. (Bad Thing)program ends. (Bad Thing)

Page 30: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Using the Error Handler

We can create an error handler by We can create an error handler by inserting the statement:inserting the statement:On Error Goto On Error Goto labellabelWhere Where labellabel is a word that occurs later in is a word that occurs later in

the code with a comma after it.the code with a comma after it.Special rules apply to these error handlers.Special rules apply to these error handlers.

Page 31: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

Comments

We’ll tuck our error handler away in a We’ll tuck our error handler away in a function so that its use will be easy to function so that its use will be easy to control. control.

This function will determine if a file This function will determine if a file exists. exists. If it does it returns trueIf it does it returns trueOtherwise it returns false.Otherwise it returns false.

Page 32: Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory

File_Exists Function

Function File_Exists (FileName as String) As IntegerFunction File_Exists (FileName as String) As IntegerOn Error Goto File_errorOn Error Goto File_error Open FileName For Input As 1Open FileName For Input As 1 Close 1Close 1 ‘If it reaches this line‘If it reaches this line File_Exists = TrueFile_Exists = True ‘the file was found‘the file was found Exit FunctionExit FunctionFile_error:File_error: ‘If it wasn’t found, control is ‘If it wasn’t found, control is File_Exists = FalseFile_Exists = False ‘here via the On Error line.‘here via the On Error line. Exit FunctionExit FunctionEnd FunctionEnd Function