Download presentation
Presentation is loading. Please wait.
1
CS 2 2/25/2015 File Exists?
2
Learning Objectives Be able to determine if a file exists before trying to reset the file Write a program using files
3
Checking if a file exists
function FileExists(FileName:string):Boolean; {It returns TRUE if the file exists; otherwise, it returns FALSE. It closes the file if it exists.} var DummyFile: file; Begin {$I-} {This turns off the error detection for file handling} Assign(DummyFile, FileName); Reset(DummyFile); Close(DummyFile); {$I+} {This turns the error checking back on} FileExists:= (IOResult = 0) and (FileName <>’’); End;
4
Some Pascal File Error Codes IOResult
2: writeln('File not found'); 3: writeln('Path not found'); 4: writeln('Too many open files'); 5: writeln('File access denied'); 100: writeln('Disk read error'); 101: writeln('Disk write error'); 150: writeln('Disk is write protected'); 152: writeln('Drive is not ready'); 154: writeln('CRC error in data'); 156: writeln('Disk seek error'); 157: writeln('Unknown media type'); 162: writeln('Hardware failure'); else writeln('Various error');
5
Example without declarations
function FileExists(FileName: string):Boolean; {It returns TRUE if the file exists; otherwise, it returns FALSE. It closes the file if it exists.} var DummyFile: file; Begin {$I-} {This turns off the error detection for file handling} Assign(DummyFile, FileName); Reset(DummyFile); Close(DummyFile); {$I+} {This turns the error checking back on} FileExists:= (IOResult = 0) and (FileName <>’’); End; If FileExists(‘stuff.dta’) then Writeln(‘The file exists and can be opened with the reset command’); Else Writeln(‘The file does not exist’); End. Can use any string.
6
To do today and Friday Using what you have learned about files, write a program with the following… Menu Create a new file Check to see if it exists before this Show all the names from the file Check to see if it exists Find if a name is in the file Check Add to an existing file. Quit Push: Let the user pick the file name. Push: Make a file of records to store the name and phone number Push: Sort the information in the file.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.