Component 9, Slide 1 CP2030 Copyright © University of Wolverhampton CP2030 Visual Basic for C++ Programmers v Component 9 working with text files and random.

Slides:



Advertisements
Similar presentations
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Advertisements

COMP234 Perl Printing Special Quotes File Handling.
File Handling Advanced Higher Programming. What is a file? Up until now, any stored data within a program is lost when the program closes. A file is a.
Files Organisation sequential files. Readings u Schneider Chapter 8 u Shelly Cashman to 9.14; to 9.11 u Meyer to 2-37; 1995.
Alford Academy Business Education and Computing1 Advanced Higher Computing Based on Heriot-Watt University Scholar Materials File Handling.
VBA Modules, Functions, Variables, and Constants
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.
Component 10a, Slide 1 CP2030 Copyright © University of Wolverhampton CP2030 Visual Basic for C++ Programmers v Component 10 – Working with Binary Files.
Guide To UNIX Using Linux Third Edition
Guide To UNIX Using Linux Third Edition
Chapter 8: I/O Streams and Data Files. In this chapter, you will learn about: – I/O file stream objects and functions – Reading and writing character-based.
Guide To UNIX Using Linux Third Edition
CHP - 9 File Structures. INTRODUCTION In some of the previous chapters, we have discussed representations of and operations on data structures. These.
1 THE UNIX FILE SYSTEM By Chokechai Chuensukanant ID COSC 513 Operating System.
Lesson 7-Creating and Changing Directories. Overview Using directories to create order. Managing files in directories. Using pathnames to manage files.
Chapter Four UNIX File Processing. 2 Lesson A Extracting Information from Files.
Guide To UNIX Using Linux Fourth Edition
Copyright © 2008 Pearson Prentice Hall. All rights reserved. 1 Microsoft Office Excel Copyright © 2008 Pearson Prentice Hall. All rights reserved
VB Games: Preparing for Memory Brainstorm controls & events Parallel structures (again), Visibility, LoadPicture, User-defined procedures, Do While/Loop,busy.
Data files and databases. Need a control to browse to a file Standard controls for drive folder and list not much use The CommonDialogs control offers.
Chapter 7 File I/O 1. File, Record & Field 2 The file is just a chunk of disk space set aside for data and given a name. The computer has no idea what.
Getting Started with MATLAB 1. Fundamentals of MATLAB 2. Different Windows of MATLAB 1.
Operating Systems COMP 4850/CISG 5550 File Systems Files Dr. James Money.
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
1 CS161 Introduction to Computer Science Topic #13.
Input and Output. Announcements  Exam Next Wednesday –Next Monday: Review session.  Invited talk: –7:30 PM,Tuesday, Oct 28th. –Prof. Katherine Socha.
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
Computer Programming TCP1224 Chapter 13 Sequential File Access.
Asking the USER for values to use in a software 1 Input.
5 1 Data Files CGI/Perl Programming By Diane Zak.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 13 File Input and.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Files & Directories.
© 1999, by Que Education and Training, Chapter 9, pages of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach.
Using Text Files in Excel File I/O Methods. Working With Text Files A file can be accessed in any of three ways: –Sequential access: By far the most common.
Programming games using Visual Basic Files; files vs. databases Reprise on state of program Lab/HW: work on projects, final project.
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
16. Python Files I/O Printing to the Screen: The simplest way to produce output is using the print statement where you can pass zero or more expressions,
Files Tutor: You will need ….
Lecture 6: Output 1.Presenting results in a professional manner 2.semicolon, disp(), fprintf() 3.Placeholders 4.Special characters 5.Format-modifiers 1.
XP New Perspectives on XML, 2 nd Edition Tutorial 7 1 TUTORIAL 7 CREATING A COMPUTATIONAL STYLESHEET.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
Introduction to Files in VB Chapter 9.1, 9.3. Overview u Data Files  random access  sequential u Working with sequential files  open, read, write,
BACS 287 File-Based Programming. BACS 287 Data Hierarchy  Database - Collection of files, relationships, integrity information, etc  Files - All records.
Controlling Program Flow with Decision Structures.
Learners Support Publications Working with Files.
Programming Fundamentals Enumerations and Functions.
Files and Streams. Objectives Learn about the classes that support file input/output Understand the concept of abstraction and how it related to the file.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
FILE I/O: Low-level 1. The Big Picture 2 Low-Level, cont. Some files are mixed format that are not readable by high- level functions such as xlsread()
Chapter 14: Sequential Access Files
Unit 2 Technology Systems
User-Written Functions
CHP - 9 File Structures.
Files and Streams Lect3 CT1411.
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Topics Introduction to File Input and Output
File IO and Strings CIS 40 – Introduction to Programming in Python
Using files Taken from notes by Dr. Neil Moore
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Chapter Four UNIX File Processing.
File Input and Output.
Visual Basic 6 Programming.
Fundamentals of visual basic
Linux Shell Script Programming
Stata Basic Course Lab 2.
Saving and Accessing Data
Topics Introduction to File Input and Output
Topics Introduction to File Input and Output
Files Chapter 8.
Presentation transcript:

Component 9, Slide 1 CP2030 Copyright © University of Wolverhampton CP2030 Visual Basic for C++ Programmers v Component 9 working with text files and random access files

Component 9, Slide 2 CP2030 Copyright © University of Wolverhampton Aims and objectives v Review the use of text files v Understand the structure of Random Access Files (RAF’s) v Use the various techniques available in Visual Basic to write to random access files. v Set the file read and write access for users and second users

Component 9, Slide 3 CP2030 Copyright © University of Wolverhampton Useful functions for handling Drives, Directories and Files v ChDrive - v ChDir- v CurDir$ - v MkDir- v RmDir - v Dir$ -

Component 9, Slide 4 CP2030 Copyright © University of Wolverhampton VB data files v VB supports three kinds of data files – Sequential (text) files store data as ACII text. Characters are read from and stored to the file character by character (see VB1) – Random-access files store data in special VB internal formats. Such files require rigid file structure – Binary files store data as individual bytes. No file structure exists, and no special internal formats are assumed v we will review text files and look at random-access files this week and binary files later in the module

Component 9, Slide 5 CP2030 Copyright © University of Wolverhampton Sequential (Text) files v Commands for handling Text files: v Useful Functions/Statement – FreeFile - – Dir$ - – Tab- – Spc-

Component 9, Slide 6 CP2030 Copyright © University of Wolverhampton Opening Text Files v Before you can use a file you must open it:  Opening for Input:  Opening for Output: v Opening for Appending:

Component 9, Slide 7 CP2030 Copyright © University of Wolverhampton Using FreeFile  We should use FreeFile to ensure we get an unused file handle: Dim iFileNum As Integer ‘get the next free file ‘open the file Open "C:\CISFILE.TXT" For Output As #iFileNum

Component 9, Slide 8 CP2030 Copyright © University of Wolverhampton Closing Files v When we have finished with a file we should close it:  Closing a specific file: Close #1 or Close #iFileNum  Closing all files: Close v It is good practice to open a file when it is needed and close it again as soon as it is finished with

Component 9, Slide 9 CP2030 Copyright © University of Wolverhampton Checking if a File Already Exists1  If you want to check if a file already exists then the best way to do this is using the Dir$() function: 'check if a normal file exists If Dir$("C:\CISFILE.TXT") <> "" Then MsgBox “The File Exists” 'open the file inside the if exists Open "C:\CISFILE.TXT" For Input As #1 ‘statements 'close the file before leaving the if exists Close #1 Else MsgBox “The File Doesn’t Exist” End If

Component 9, Slide 10 CP2030 Copyright © University of Wolverhampton Checking if a File Already Exists2 v You can also use symbolic file attribute constants: Symbolic ConstantValueMeaning ATTR_NORMAL 0 ATTR_HIDDEN 2 ATTR_SYSTEM 4 ATTR_VOLUME 8 ATTR_DIRECTORY 16 'check if a directory exists If Dir$("C:\CISDIR",ATTR_DIRECTORY) <> "" Then MsgBox “The Sub Directory Exists” End If v You can, of course, combine file attribute constants

Component 9, Slide 11 CP2030 Copyright © University of Wolverhampton Printing To Text Files 1 v Once a file has been opened for Output or Appending we can either Print or Write information to it  Print # Statement: Open "TESTFILE.TXT" For Output As #1 Print #1, "Test of the Print # statement" ' Print blank line to file Print #1, ' Print in two print zones iValue = 12 Print #1, ”Value is", iValue ' Print two strings together Print #1, "With no space between" ; "." Close #1

Component 9, Slide 12 CP2030 Copyright © University of Wolverhampton Printing To Text Files 2 v File: v Notice effects of “,” and “;” in layout of fields

Component 9, Slide 13 CP2030 Copyright © University of Wolverhampton Printing To Text Files - Tab Function v There are two functions available which can help the programmer with formatting the layout of a file when using Print #  Tab function: Open "TEST2.TXT" For Output As #1 Print #1,"This is a Tab";Tab(20);"function test." Print #1, "Get the"; Tab(20); "idea?" Close #1  File: This is a Tab function test. Get the idea?

Component 9, Slide 14 CP2030 Copyright © University of Wolverhampton Printing To Text Files Spc Function  Spc function: ' open file for output Open "TEST3.TXT" For Output As #1 Print #1, "This is a Spc function”;Spc(10);"test." ' close file Close #1  File: This is a Spc function test.

Component 9, Slide 15 CP2030 Copyright © University of Wolverhampton Line Input From Text Files 1  Line Input # is the 'opposite' of Print #, as it reads everything that is on the line in the file: Dim sInBuffer As String Open "C:\TESTFILE.TXT" For Input As #1 Line Input #1, sInBuffer Label1.Caption = sInBuffer + chr(13) Line Input #1, sInBuffer Label1.Caption = Label1.Caption + sInBuffer + chr(13) Line Input #1, sInBuffer Label1.Caption = Label1.Caption + sInBuffer + chr(13) Line Input #1, sInBuffer Label1.Caption = Label1.Caption + sInBuffer + chr(13) Close #1

Component 9, Slide 16 CP2030 Copyright © University of Wolverhampton Line Input From Text Files 2  TESTFILE.TXT Test of the Print # statement Value is 12 With no space between.  Label1.Caption = Test of the Print # statement Value is 12 With no space between. v Note: Data is read line-by-line; not as separate fields

Component 9, Slide 17 CP2030 Copyright © University of Wolverhampton Line Input From Text Files: EOF Function  If we don't know how many lines there are in a file then we can loop and use the EOF() function to check for the end of the file: Dim sInBuffer As String ‘open the file Open "C:\TEST3.TXT" For Input As #1 ‘blank the label to start with Label1.Caption = "" ‘while it’s not the end of file While Not EOF(1) ‘get line & place in label Line Input #1, sInBuffer Label1.Caption = Label1.Caption +sInBuffer +chr(13) Wend Close #1 ‘close the file

Component 9, Slide 18 CP2030 Copyright © University of Wolverhampton Line Input From Text Files 3 v Looping while it isn’t the end of file produces the same results as before:  TEST3.TXT This is a sample text file which contains four lines!  Label1.Caption = This is a sample text file which contains four lines!

Component 9, Slide 19 CP2030 Copyright © University of Wolverhampton Writing To Text Files 1 v For a file which has been opened for Output or Appending we can use Write instead of Print  Write # Statement: Open ”U:\TESTFILE.TXT" For Output As #1 Write #1,"This is a test of the Write # statement." ' Write blank line to file Write #1, ' Write three fields on the same line iValue = 12 Write #1,"Numbers ", iValue; 20 Write #1,"End Test" Close #1

Component 9, Slide 20 CP2030 Copyright © University of Wolverhampton Writing To Text Files 2 The file produced looks like: v Note that the blank line has nothing on it; also semi-colon separator replaced by comma v Compare this with the file created by Print # v User-defined data types cannot be written in one piece; they must be written to file as separate fields

Component 9, Slide 21 CP2030 Copyright © University of Wolverhampton Input #… reading back from a file created with Write # Dim sInBuffer As String Dim iVal1 As Integer, iVal2 As Integer Open "U:\TESTFILE.TXT" For Input As #2 Input #2, sInBuffer label1.Caption = sInBuffer Input #2, sInBuffer, iVal1, iVal2 label1.Caption = label1.Caption + Chr(13) + sInBuffer label1.Caption = label1.Caption + Str(iVal1) + " + " + Str(iVal2) + " = " label1.Caption = label1.Caption + Str(iVal1 + iVal2) + Chr(13) Input #2, sInBuffer label1.Caption = label1.Caption + Chr(13) + sInBuffer Close #2

Component 9, Slide 22 CP2030 Copyright © University of Wolverhampton Input From Text Files 2  TESTFILE.TXT "This is a test of the Write # statement." "Numbers",12,20 "End Test"  Label1.Caption This is a test of the Write # statement. Numbers = 32 End Test Note: format of the written text file, and how each field has to be read in separately.

Component 9, Slide 23 CP2030 Copyright © University of Wolverhampton Random Access Files v In a Sequential File, a particular record may only be accessed by reading sequentially through the file, from the beginning v In a Random Access file, a particular record may be accessed directly, without reading all preceding records. v A Random Access file is like an array of records, but stored on disk. v Random Access files are also known as Direct Access or Relative files.

Component 9, Slide 24 CP2030 Copyright © University of Wolverhampton File structure v All records in a Random Access file must be the same size. v Each record has a unique record number; representing its location in the file. v Using the record length and the record number a particular record can be located directly v Records typically are created using a user-defined type.

Component 9, Slide 25 CP2030 Copyright © University of Wolverhampton Steps to process a RAF Use the following four steps to process RAFs with record variables 1 define a record variable matching your data template 2 open the File For Random 3 Use a record variable in Get and Put instructions to read and write the data 4 Close the file

Component 9, Slide 26 CP2030 Copyright © University of Wolverhampton Random Access Files and User Defined Types v User defined types lend themselves ideally to use with random access files as they have a set number of elements in each record v take a file for holding info. on a stamp collection as an example. We will store the information as shown, with the size of each data field being fixed by the user or by the data type used

Component 9, Slide 27 CP2030 Copyright © University of Wolverhampton 1st Step to process the RAF 1define a user defined type matching your data template v in our case it will look like Type Stamptype iYear as integer sCountry as string * 18 ‘ max string length 18 fValue as single sComment as string * 60 ‘ max string length 60 End Type Dim uStamp as Stamptype

Component 9, Slide 28 CP2030 Copyright © University of Wolverhampton 2nd step - opening the file 2.A random access file can only be opened as Random, unlike the sequential file where Append, Input and Output can be used. v The syntax is as follows: Open filename For Random As #filenum Len = recordlength where filename is the filename and path #filenum is the filehandle number recordlength is the number of bytes in the record e.g. applying this to our stamp collection database Open “c:\temp\stamp.ran” For Random As #1 Len = 84

Component 9, Slide 29 CP2030 Copyright © University of Wolverhampton Length of user-defined data type v To save you having to work out the length of your data type you can use the Len(..) function Dim uStamp as StampType Open “c:\temp\stamp.ran” For Random As #1 Len = Len(uStamp)

Component 9, Slide 30 CP2030 Copyright © University of Wolverhampton 3rd step - writing and reading records v We can use the Put statement to write to a random file record v It has the form Put #filenum, recordnum, variable in our stamp collection example this would be: Put #1, 12, stamp - recordnum is optional - default is the one after last record written to

Component 9, Slide 31 CP2030 Copyright © University of Wolverhampton 3rd step Reading from a RAF use the Get statement Get #filenum, recordnum, variable in our stamp collection example this would be: Get #1, 12, stamp - where stamp specifies the Variable to receive the data - again recordnum is optional - default is the one after last record read from

Component 9, Slide 32 CP2030 Copyright © University of Wolverhampton More info on Recordnum v As the file is random access - recordnum can be any value above 0. v You can Put data to record number 12 when you have only written data records 1 to 4 previously. v You can Get data from any existing record by specifying its number

Component 9, Slide 33 CP2030 Copyright © University of Wolverhampton 4th step - closing the file As with all file handling work it is important to Close the file when all i/o activity has finished format Close #filenum e.g. Close #1

Component 9, Slide 34 CP2030 Copyright © University of Wolverhampton Seek function v If you have a complex programme and it is difficult to keep track of what record was last written to or read from - use the Seek function which returns the number of the record after the last one you have either written to or read from. Format Seek (filenum) - where the # sign is omitted e.g iNextRecordToOpen = Seek(1)

Component 9, Slide 35 CP2030 Copyright © University of Wolverhampton Seek Statement v Seek statement sets the file pointer to the next record you want to read or write to Format Seek filenum, recordnum, After this Seek a Get or Put statement without a recordnum parameter operates on this newly reset file position e.g Seek #9, 23 ‘ move pointer to the 23rd record of file number 9 Put #9,, uStamp ‘ write the data from uStamp in the 23rd record ‘ of file number 9

Component 9, Slide 36 CP2030 Copyright © University of Wolverhampton Opening files in a network environment v On a network two users running independently may want to open a specific file at the same time. VB offers some control as to the scope of file sharing privileges. v The Open statement allows the setting of these access permissions for the user using the Access clause Format Open filespec For Random Access accessmode lockmode As #Filenum Len = recordlength where accessmode has the options of: Read - read only Write - write only Read Write - read and write

Component 9, Slide 37 CP2030 Copyright © University of Wolverhampton Opening files in a network environment - cont. lockmode - specifies the type of access that other users have to the open file. Has the options of :- (default) if lockmode not specified only one user can open file at a time Shared Multiple users can open the file jointly Lock Read No other user can read from the file Lock Write No other user can write to the file Lock Read Write No other user can access the file e.g Open “c:\temp\stamp.ran” For Random Access Read Lock Read As #1 Len = 84 Here the file is opened as read only and no other can read it at the same time

Component 9, Slide 38 CP2030 Copyright © University of Wolverhampton Summary v We have investigated – the file structure of the Random file type – how we can map reading and writing to a random file using user defined types with the Get and Put statement – the use of the Seek function and statement to point to a particular record or return the next record number to write to or read from – how to set the access rights for users and second users