Presentation is loading. Please wait.

Presentation is loading. Please wait.

© 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach.

Similar presentations


Presentation on theme: "© 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach."— Presentation transcript:

1 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach Data File Hierarchy/Terminology n Folder or Directory i A container for 0 or more files accessible from the same location. n File i A collection of related records stored as a unit on external media. n Record or Row i A collection of related fields such as many pieces of information about a person or thing. n Field i A single (meaningful) piece of information about a person or thing. n Byte i Normally a collection of one or more characters that comprise a field (character ~ byte) n Bit i Commonly written as 0 or 1 as the smallest unit of computer data. i Generally 8 bits = 1 byte, yielding 256 combinations--ASCII code

2 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach Data File Hierarchy Example n Folder or Directory i For class files called Courses n File i The file CPT250Grades.txt inside the Courses folder holds all class information for one course. n Record or Row i Each record in the grades file contains Student Name, Student ID, three test grades and ten project grades. n Field i Student ID is comprised of the last 5 digits of the social security number. n Byte i Each character of the ID requires one byte of storage. n Bit i The character “2” of the student ID has the ASCII code 50, which is written as 00110010, where each symbol is a bit.

3 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach Physical Details of Files n Before you can write programs that use files, you need to get answers to the following: i Can records be accessed sequentially? i Can records be accessed arbitrarily? i Do all of the records have the same length? i How are the fields ordered on each record? i What is the data type of each field? i Is the length of each field the same? i How are the fields separated?

4 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach Different Types of Files n Random-access data files i Files designed to facilitate future retrieval of individual records in an arbitrary order. i Retrieving a record requires determining its location u Hashing u Index (ISAM) i Thus, it is logically used like an array but data resides on disk n Binary data files i A machine-readable format that can contain almost anything i Unreadable if loaded in a word processor or text editor i Program files u Special type of binary file that the OS can interpret with the right OCXs, DLLs, EXEs.

5 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach Different Types of Files n Sequential data files i Data elements stored and retrieved one after another, in order i Examples u Text files (Report-Record or Display-Formatted format) –Simple documents such as README files created with ASCII text editor like Notepad –Designed to be read, so there are no field delimiters –Carriage return and line feed mark the end of each line u Comma-separated value (CSV) files –Common means for transferring data across applications –Contains variable length records separated by commas –Certain types of data are surrounded by special characters –Carriage return and line feed mark the end of each line/record u Fixed-width data files –Commonly created from/for COBOL programs

6 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach General usage of Files 1)Assign a file number i To refer to file in subsequent file access statements 2) Open the file i Identify file name & path, purpose, reference number, and record length if random file 3)Read/Write the file (possibly within a loop) i Specify reference number, action, and data elements u Read retrieves data from the file into specified memory locations (variables) u Write copies data in specified memory locations (variables) to current location in file 4)Close the file i Specify reference number to release the number and the file

7 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach Assigning a File Number n Two choices i Use a literal constant (between 1-511) i Use FreeFile function to have VB automatically assign an available reference number i Use caution when working with multiple files simultaneously n Incorrect Dim InNbr As Integer Dim OtNbr As Integer InNbr = FreeFile ' Returns 1. OtNbr = FreeFile ' Returns 1. Open "Input.dat" For Input As #InNbr Open "Output.dat" For Output As #OtNbr n Correct Dim InNbr As Integer Dim OtNbr As Integer InNbr = FreeFile ' Returns 1. Open "Input.dat" For Input As #InNbr OtNbr = FreeFile ' Returns 2. Open "Output.dat" For Output As #OtNbr

8 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach Opening a File n Provide information about the file before any access Open pathname For mode {Access access} {lock} _ As #filenumber {Len = recordlength} n Elements of Open statement i pathname: a string that defines the file name with full path i mode: (purpose: input, output, append, random, binary) u Establishes record pointer at start of file for all modes but append which starts at end of file i access: specifies allowable operations (needed with random) i lock: specifies allowable operations by other processes (n/a) i filenumber: reference number used in subsequent read/write operations i recordlength: number of bytes in a record of a random access file or buffer size for sequential files

9 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach Reading from a File n CSV file Input #filenumber, VariableList u Data read from current location of file pointer into corresponding variables u Each comma or end-of-line delimits each field, unless surrounded in quotations u Normally, records were created using the Write statement

10 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach Reading from a File n Report (display-formatted) file Line Input #filenumber, VariableName u Read the next line from current location of file pointer into specified variable u Normally, records were created using the Print statement n Fixed record-length file Get #filenumber, {recordnumber}, VariableName u Read the next record from current location of file pointer into specified variable u Needed by fixed-record length files since there is no end- of-line character u Normally, records were created using the Put statement

11 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach Detecting End-of-File n Use EOF function i Special function that detects when the end of file has been reached EOF(filenumber) n Use Data sentinel i Record that contains specific, fixed values, which, when read, signal the last record has been processed n Use unique first record that defines the number of records that follow i Atypical approach that allows counting loop to be used to read the fixed number of records n Error handler to detect read past end of file error

12 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach Writing to a File n CSV file Write #filenumber, VariableList u Data in variable list written to current file location u Comma inserted between fields, carriage-return and line feed inserted at end of record, quotations placed around strings and # around Booleans and dates u Normally, records will be read using Input statement

13 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach Writing to a File n Report (display-formatted) file Print #filenumber, OutputList u Print the output list to next line in file unless previous Print ended in comma or semicolon –May contain expressions, Spc(n), Tab(n), separated by comma or semicolon u Normally, records will be read using Line Input statement n Fixed record-length file Put #filenumber, {recordnumber}, VariableName u Write the data in VariableName to current file location u Normally, records will be retrieved using the Get statement

14 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach Closing a File n Notifies the operating system that you are done with the file Close {{#}filenumberlist} i Examples u Close #EmpFile, #TaxFile u Close i For output files, the buffers are flushed to insure that everything gets written to the file. i When reading the same file more than once in a single session, you must open and close each time.

15 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach ‘ use static arrays and literal RefNbr Open “file” For Input As #1 Input #1, EndVal For Count = 1 To EndVal Step 1 Input #1, Array(Count) ‘ steps to process repeatedly Next Count Close #1 Reading Files with pre-data n When pre-data is included at start of data file or the program knows the number of records, use For/Next counting loop n Loop condition compares loop counter against the number of records read so far False True Count > EndVal? Set Count = 1 Count = Count + 1 Open file for input (#1) Input #1, EndVal Input #1, Array(Count) Other steps to process in loop Close #1

16 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach False True TempVar = Sentinel data Set Count = 0 Count = Count + 1 Open file for input (#1) Input #1, TempVar Other steps to process in loop Close #1 Input #1, TempVar Array(Count) = TempVar Reading Files with post-data data Pre-test loop to check for sentinel data ‘ use static arrays and literal RefNbr Open “file” For Input As #1 Input #1, TempVar Count = 0 Do Until TempVar = SentinelData Count = Count + 1 Array(Count) = TempVar ‘ steps to process repeatedly Input #1, TempVar Loop Close #1

17 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach Reading Files with no pre/post data Pre-conditional loop to check EOF ‘ use static arrays and literal RefNbr Open “file” For Input As #1 Count = 0 Do Until EOF(1) Count = Count + 1 Input #1, Array(Count) ‘ steps to process repeatedly Loop Close #1 **This is the most likely approach when files are used False True EOF(1) Set Count = 0 Count = Count + 1 Open file for input (#1) Input #1, Array(Count) Other steps to process in loop Close #1

18 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach How does reading a CSV file work? n Open statement i Record pointer set to start of file (before first record) n Each time an input statement is processed i For each variable listed u Type of data in field must be compatible with the data type of the corresponding variable where it will be stored u Data at file’s record pointer is read and stored in corresponding, named field (variable) u Record pointer moves to the start of the next field (whether on same line or next line) n Close statement to release file to OS

19 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach VB Statements to Read CSV File ' Use dynamic array and FreeFile function Dim EmpCount As Integer Dim CsvInFile As Integer CsvInFile = FreeFile ' Returns 1. Open “a:\sample.csv” For Input As #CsvInFile Do Until EOF(CsvInFile) EmpCount = UBound(fEmp) + 1 ReDim Preserve fEmp(0 To EmpCount) As EmpType Input #CsvInFile, fEmp(EmpCount).ID, _ fEmp(EmpCount).Name, fEmp(EmpCount).Rate, _ fEmp(EmpCount).Hours ' optional code to process employee’s data Loop Close #CsvInFile

20 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach How does writing a CSV file work? n Open statement i New file created in stated path with given name i Output mode u Record pointer is set to the start of the file i Append mode u Record pointer is set to the end of the file n Each time a write statement is processed i For each variable listed u Data in memory (variable) is written at record pointer –Strings enclosed in double quotes & Boolean and dates enclosed in # –Comma separator used unless last variable in list i Carriage return-line feed mark the end of the line n Close statement to release file to OS

21 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach How does reading a report file work? n Open statement i same as writing CSV file n Each time a print statement is processed i Start on a new line unless the previous print ended in a comma “,” or semicolon “;” i For each expression listed u Data is written at current file pointer –Expressions separated by semicolons “;” keep file pointer where it left off –Expressions separated by commas “,” move pointer to next print zone n Close statement to release file to OS

22 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach VB Statements to Write CSV File ' Use dynamic array and FreeFile function Dim Index As Integer Dim EmpCount As Integer Dim CsvOutFile As Integer CsvOutFile = FreeFile ' Returns 1. Open “a:\sample.csv” For Output As #CsvOutFile EmpCount = UBound(fEmp) For Index = 1 To EmpCount Step 1 Write #CsvOutFile, fEmp(EmpCount).ID, _ fEmp(EmpCount).Name, fEmp(EmpCount).Rate, _ fEmp(EmpCount).Hours Next Index Close #CsvOutFile

23 © 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach Before using Sequential Files n You must determine or plan its structure i Number of records u To determine type of loop processing & size of array(s) needed i Number, order, and type of fields per record u To determine the fields (generally on one line) –if different types: for the user-defined array –if same type: number of columns for 2-d array i Pre-data u Generally the number of following records (counting loop) i Post-data (Sentinel data) u If present, to flag when the last good data set has been reached i If no pre-data or post-data, may use EOF function or write error handler to determine when end of file reached


Download ppt "© 1999, by Que Education and Training, Chapter 9, pages 447-483 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach."

Similar presentations


Ads by Google