File I/O

Under MS Windows, file and directory names must not contain and should not contain because they are used as NT 4.0 command-line paramters.

Visual Basic | Delphi | Visual C++

Visual Basic 6.0

File Manager Commands

Change Directory ChDir "c:\path"
Make Directory MkDir "c:\path"
Remove Directory RmDir "c:\path"
Change Drive ChDrive "d"
Rename a File Name "test.txt" as "string.tst"
(May fail if directories are not specified)
Delete a File Kill "c:\*.tst"
Search for File temp$ = Dir ("c:\*.tst")
Current Drirectory temp$ = CurDir ("d") ' Drive letter is optional
Get File Attributes temp = GetAttr ("c:\filename.tst")
Get File Mode temp = FileAttr ("c:\filename.tst", attributes)
Set File Attributes SetAttr "c:\filename.tst", vbReadOnly
Get File Length FileLen ("c:\filename.tst")
Get File Date/Time tempDate = FileDateTime ("c:\filename.tst")
Set File Date/Time ????

File I/O Commands

Open File for I/O Open "c:\filename.tst" For Input As 3
fn = FreeFile ' next unused number
Open "c:\filename.tst" For Input As fn
Get File Mode temp = FileAttr (3, 1)
Write to File Write 3, - Places strings in double quotes
Print 3, - Strings without double quotes
Read From File Input 3,
Get 3,
Line Input #FileHandle, TextLine$
Current Location tempNum = Seek (3)
tempNum = Loc (3)
Length of File tempNum = LOF(3)
End of File Do While Not EOF(3) .. Loop
Close File Close 3
Closes All Files Reset

Write places strings in double quotes, separates values with commas, and adds a CR/LF pair at the end of each command. Read the data back with Input.

Print does not add extra delimiters, but does concatenate a final CR/LF to each line. The CR/LF can be suppressed by ending the command with a semicolon (;). (This trick has been available in every Basic I've used, but it is not documented in the VB 6.0 Help.) Read it back with Line Input. (Line Input assumes a DOS type ASCII input file where each line is terminated with CR/LF. It does not recognize the unix line termination character.)

Visual Basic 6.0 Examples

File Access via a FileSystemObject
VB 6.0 provides a poorly documented FileSystemObject for File I/O. Help on these commands was found be basically "stumbling" onto them. This is the only File I/O method supported via VBScript.

Standard Open File Dialog
Based on the provided help, there is no way to open a file using the provided components. This explains how to use the File Open dialog.

Specifying a Drive and Path
How to use the DirListBox control to specify a path and the DriveListBox control to change drives.

Opening and Reading a File

File SaveAs

Testing for a Legal Filename
The are a number of characters that directory and file names can not contain. This code verifies that the directory or filename is legal.

Testing for the Existance of a File
This shows 2 methods to determine whether or not the file exists. one method allows wild cards.

Testing for the Existance of a Drive
This is a fairly complex example from comp.lang.basic.visual.misc


Use of the non-native Pascal file variable handlers such as FileOpen is discouraged. These routines map to the Windows API functions and return file handles, not normal Pascal file variables. These are low-level file access routines. For normal file operations use the normal AssignFile, Rewrite, Reset operations instead of FileOpen. (From the Delphi FileOpen help.)

File Manager Commands

SysUtils/FileOpen and System/AssignFile have different commands for many of these

See SysUtils / File-management routines and System / I/O routines

Change Directory SetCurrentDir('c:\path')
Make Directory CreateDir('c:\path')
Remove Directory RemoveDir('c:\path')
Change Drive ChDir('c:') (need to test)
Rename a File RenameFile('test.txt', 'string.tst')
ChangeFileExt('test.txt', 'doc') (only generates a string)
Delete a File DeleteFile('c:\*.tst') - Don't know if wildcards are allowed
Search for File t_str := FileSearch('readme.txt', 'c:\;c:\windows')
t_int := FindFirst ('c:\*.tst', attr, F)
Current Drirectory t_str := GetCurrentDir ;
GetDir (4, t_str) // d-drive
Get File Attributes temp = FileGetAttr('c:\filename.tst')
Set File Attributes FileSetAttr('c:\filename.tst', faReadOnly)
Get File Length FileSize(var F)
Get File Date/Time tempDate := FileGetDate(Handle)
tempDate := FileAge('c:\filename.tst')
Set File Date/Time FileSetDate(Handle, Age)
Test File existance if FileExists('c:\filename.tst') then
if DirectoryExists('c:\temp') then

AdjustLinesBreaks(const S: string): string; - adjusts all line breaks in the string S to be true CR/LF

From the FileSearch example, not documented elsewhere -

File I/O Commands

Open File for I/O FileOpen(const FileName: string; Mode: Integer): Integer;
AssignFile(F, OpenDialog1.FileName);
Reset(F); // Open for FileMode (Read, Write, Read/Write)
Rewrite(var F: File [; Recsize: Word ] );
Get File Mode F.Mode or (F as TFileRec).Mode
Write to File FileWrite(Handle: Integer; const Buffer; Count: Integer): Integer;
Write to TextFile Writeln, Write
Read From TextFile Read, Readln
Read From File BlockRead
Current Location Seek (F1, 3) - Zero based
Current Location tempNum := FilePos (F1);
Length of File tempNum := FileSize(f1);
End of File while not Eof(F1) do
Close File FileClose(Handle: Integer)
Closes All Files not available

  f1 : file;      // Generic
  f2 : text;
  f3 : textfile;  // from AssignFile help

(* File type declarations from Delphi file help *)
  Person = record
    FirstName: string[15];
    LastName : string[25];
    Address  : string[35];
  PersonFile = file of Person;   // Fixed structure
  NumberFile = file of Integer;
  SwapFile = file;

TFileRec = record
  Handle: Integer;
  Mode: Integer;
  RecSize: Cardinal;
  Private: array[1..28] of Byte;
  UserData: array[1..32] of Byte;
  Name: array[0..259] of Char;

Filename Utilities

Delphi provides numerous functions to process filenames, including

Add a trailing \ IncludeTrailingBackslash
Remove a trailing \ ExcludeTrailingBackslash
Parse the path ProcessPath
Convert to 8.3 ExtractShortPathName
Get a part ExtractFileDrive
ExtractFileDir - includes drive letter
ExtractFilePath - omits drive letter
Replace the extension ChangeFileExt

See File name utilities in the help.

Delphi 2.0 Examples

File Search Commands
Files and directories may not have the same names. The more complicated FindFirst command must be used because FileExists does not find directories.

Testing for the Existance of a File
This example is from the Delphi help.

Testing for the Existance of a Directory

Opening and Reading a File
These 2 examples demonstrate the use of the FileOpen dialog box and use the Pascal type TextFile I/O commands including Readln (read a text line) and Writeln.

Additional Info

Filemanager Toolset 2.6 provides free components and source to manage lists of files and directories.

Visual C++

For information using fstream.

Author: Robert Clemenzi -
URL: http:// / user / clemenzi / technical / Languages / FileIO.htm