FileAccess Tcl Reference Documentation

FileAccess

API for reading and writing files, creating and deleting directories, deleting directory trees, splitting and re-joining large files, etc. This is a freeware class. The reason for its existence is that in some programming languages, file I/O API's are limited or difficult to understand/use. This API provides an identical FILE I/O API across all programming languages supported by Chilkat.

Object Creation

set myFileAccess [new CkFileAccess]

Properties

CurrentDir (string)

# ckStr is a CkString
CkFileAccess_get_CurrentDir $myFileAccess $ckStr
set strVal [CkFileAccess_get_currentDir $myFileAccess]

The current working directory of the calling process.

DebugLogFilePath (string)

# ckStr is a CkString
CkFileAccess_get_DebugLogFilePath $myFileAccess $ckStr
set strVal [CkFileAccess_get_debugLogFilePath $myFileAccess]
CkFileAccess_put_DebugLogFilePath $myFileAccess $strVal

If set to a file path, causes each Chilkat method or property call to automatically append it's LastErrorText to the specified log file. The information is appended such that if a hang or crash occurs, it is possible to see the context in which the problem occurred, as well as a history of all Chilkat calls up to the point of the problem. The VerboseLogging property can be set to provide more detailed information.

This property is typically used for debugging the rare cases where a Chilkat method call hangs or generates an exception that halts program execution (i.e. crashes). A hang or crash should generally never happen. The typical causes of a hang are:

  1. a timeout related property was set to 0 to explicitly indicate that an infinite timeout is desired,
  2. the hang is actually a hang within an event callback (i.e. it is a hang within the application code), or
  3. there is an internal problem (bug) in the Chilkat code that causes the hang.

EndOfFile (boolean 1/0)

set boolVal [CkFileAccess_get_EndOfFile $myFileAccess]

Returns 1 if the current open file is at the end-of-file.

FileOpenError (integer)

set intVal [CkFileAccess_get_FileOpenError $myFileAccess]

This property is set by the following methods: FileOpen, OpenForRead, OpenForWrite, OpenForReadWrite, and OpenForAppend. It provides an error code indicating the failure reason. Possible values are:

  1. Success (No error)
  2. Access denied.
  3. File not found.
  4. General (non-specific) open error.
  5. File aleady exists.
  6. Path refers to a directory and the access requested involves writing.
  7. Too many symbolic links were encountered in resolving path.
  8. The process already has the maximum number of files open.
  9. Pathname is too long.
  10. The system limit on the total number of open files has been reached.
  11. Pathname refers to a device special file and no corresponding device exists.
  12. Insufficient kernel memory was available.
  13. Pathname was to be created but the device containing pathname has no room for the new file.
  14. A component used as a directory in pathname is not, in fact, a directory.
  15. Pathname refers to a regular file, too large to be opened (this would be a limitation of the underlying operating system, not a limitation imposed by Chilkat).
  16. Pathname refers to a file on a read-only filesystem and write access was requested.

FileOpenErrorMsg (string)

# ckStr is a CkString
CkFileAccess_get_FileOpenErrorMsg $myFileAccess $ckStr
set strVal [CkFileAccess_get_fileOpenErrorMsg $myFileAccess]

The error message text associated with the FileOpenError code.

LastErrorHtml (string)

# ckStr is a CkString
CkFileAccess_get_LastErrorHtml $myFileAccess $ckStr
set strVal [CkFileAccess_get_lastErrorHtml $myFileAccess]

Provides information in HTML format about the last method/property called. If a method call returns a value indicating failure, or behaves unexpectedly, examine this property to get more information.

LastErrorText (string)

# ckStr is a CkString
CkFileAccess_get_LastErrorText $myFileAccess $ckStr
set strVal [CkFileAccess_get_lastErrorText $myFileAccess]

Provides information in plain-text format about the last method/property called. If a method call returns a value indicating failure, or behaves unexpectedly, examine this property to get more information.

Concept of LastErrorText

LastErrorText Standard Information

LastErrorXml (string)

# ckStr is a CkString
CkFileAccess_get_LastErrorXml $myFileAccess $ckStr
set strVal [CkFileAccess_get_lastErrorXml $myFileAccess]

Provides information in XML format about the last method/property called. If a method call returns a value indicating failure, or behaves unexpectedly, examine this property to get more information.

LastMethodSuccess (boolean 1/0)

set boolVal [CkFileAccess_get_LastMethodSuccess $myFileAccess]
CkFileAccess_put_LastMethodSuccess $myFileAccess $boolVal

Introduced in version 9.5.0.52

Indicate whether the last method call succeeded or failed. A value of 1 indicates success, a value of 0 indicates failure. This property is automatically set for method calls. It is not modified by property accesses. The property is automatically set to indicate success for the following types of method calls:

  • Any method that returns a string.
  • Any method returning a Chilkat object, binary bytes, or a date/time.
  • Any method returning a standard boolean status value where success = 1 and failure = 0.
  • Any method returning an integer where failure is defined by a return value less than zero.

Note: Methods that do not fit the above requirements will always set this property equal to 1. For example, a method that returns no value (such as a "void" in C++) will technically always succeed.

Utf8 (boolean 1/0)

set boolVal [CkFileAccess_get_Utf8 $myFileAccess]
CkFileAccess_put_Utf8 $myFileAccess $boolVal

When set to 1, all "const char *" arguments are interpreted as utf-8 strings. If set to 0 (the default), then "const char *" arguments are interpreted as ANSI strings. Also, when set to 1, and Chilkat method returning a "const char *" is returning the utf-8 representation. If set to 0, all "const char *" return values are ANSI strings.

VerboseLogging (boolean 1/0)

set boolVal [CkFileAccess_get_VerboseLogging $myFileAccess]
CkFileAccess_put_VerboseLogging $myFileAccess $boolVal

If set to 1, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is 0. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.

Version (string)

# ckStr is a CkString
CkFileAccess_get_Version $myFileAccess $ckStr
set strVal [CkFileAccess_get_version $myFileAccess]

Version of the component/library, such as "9.5.0.63"

Methods

# text is a string
set status [CkFileAccess_AppendAnsi $text]

Appends a string using the ANSI character encoding to the currently open file.

Returns 1 for success, 0 for failure.

# str is a string
# charset is a string
set status [CkFileAccess_AppendText $str $charset]

Appends a string using the character encoding specified by str to the currently open file.

Returns 1 for success, 0 for failure.

set status [CkFileAccess_AppendUnicodeBOM]

Appends the 2-byte Unicode BOM (little endian) to the currently open file.

Returns 1 for success, 0 for failure.

set status [CkFileAccess_AppendUtf8BOM]

Appends the 3-byte utf-8 BOM to the currently open file.

Returns 1 for success, 0 for failure.

# filePath is a string
set status [CkFileAccess_DirAutoCreate $filePath]

Same as DirEnsureExists, except the argument is a file path (the last part of the path is a filename and not a directory). Creates all missing directories such that filePath may be created.

Returns 1 for success, 0 for failure.

# dirPath is a string
set status [CkFileAccess_DirCreate $dirPath]

Creates a new directory specified by dirPath.

Returns 1 for success, 0 for failure.

# dirPath is a string
set status [CkFileAccess_DirDelete $dirPath]

Deletes the directory specified by dirPath.

Returns 1 for success, 0 for failure.

# dirPath is a string
set status [CkFileAccess_DirEnsureExists $dirPath]

Creates all directories necessary such that the entire dirPath exists.

Returns 1 for success, 0 for failure.

CkFileAccess_FileClose

Closes the currently open file.

# filePath1 is a string
# filePath2 is a string
set retBool [CkFileAccess_FileContentsEqual $filePath1 $filePath2]

Compares the contents of two files and returns 1 if they are equal and otherwise returns 0. The actual contents of the files are only compared if the sizes are equal. The files are not entirely loaded into memory. Instead, they are compared chunk by chunk. This allows for any size files to be compared, regardless of the memory capacity of the computer.

# existingFilepath is a string
# newFilepath is a string
# failIfExists is a boolean
set status [CkFileAccess_FileCopy $existingFilepath $newFilepath $failIfExists]

Copys existingFilepath to newFilepath. If failIfExists is 1 and newFilepath already exists, then an error is returned.

Returns 1 for success, 0 for failure.

# filePath is a string
set status [CkFileAccess_FileDelete $filePath]

Deletes the file specified by filePath.

Returns 1 for success, 0 for failure.

# filePath is a string
set retBool [CkFileAccess_FileExists $filePath]

Returns 1 if filePath exists, otherwise returns 0.

# path is a string
set retInt [CkFileAccess_FileExists3 $path]

Introduced in version 9.5.0.45

Returns 1 if the file exists, 0 if the file does not exist, and -1 if unable to check because of directory permissions or some other error that prevents the ability to obtain the information.

# filePath is a string
# accessMode is an integer
# shareMode is an integer
# createDisposition is an integer
# attributes is an integer
set status [CkFileAccess_FileOpen $filePath $accessMode $shareMode $createDisposition $attributes]

This method should only be called on Windows operating systems. It's arguments are similar to the Windows Platform SDK function named CreateFile. For Linux, MAC OS X, and other operating system, use the OpenForRead, OpenForWrite, OpenForReadWrite, and OpenForAppend methods.

Opens a file for reading or writing. The arguments mirror the Windows CreateFile function:

Access Modes:
GENERIC_READ	(0x80000000)
GENERIC_WRITE (0x40000000)

Share Modes:
FILE_SHARE_READ(0x00000001)
FILE_SHARE_WRITE(0x00000002)

Create Dispositions
CREATE_NEW          1
CREATE_ALWAYS       2
OPEN_EXISTING       3
OPEN_ALWAYS         4
TRUNCATE_EXISTING   5

// Attributes:
FILE_ATTRIBUTE_READONLY         0x00000001
FILE_ATTRIBUTE_HIDDEN           0x00000002
FILE_ATTRIBUTE_SYSTEM           0x00000004
FILE_ATTRIBUTE_DIRECTORY        0x00000010
FILE_ATTRIBUTE_ARCHIVE          0x00000020
FILE_ATTRIBUTE_NORMAL           0x00000080
FILE_ATTRIBUTE_TEMPORARY	   0x00000100

Returns 1 for success, 0 for failure.

# maxNumBytes is an integer
# outBytes is a CkByteData (output)
set status [CkFileAccess_FileRead $maxNumBytes $outData]

Reads bytes from the currently open file. maxNumBytes specifies the maximum number of bytes to read. Returns an empty byte array on error.

Returns 1 for success, 0 for failure.

# maxNumBytes is an integer
# binData is a CkBinData
set status [CkFileAccess_FileReadBd $maxNumBytes $binData]

Introduced in version 9.5.0.64

Reads bytes from the currently open file. maxNumBytes specifies the maximum number of bytes to read. Appends the bytes to the binData.

Returns 1 for success, 0 for failure.

Determine File Type from Binary Content of File

# existingFilepath is a string
# newFilepath is a string
set status [CkFileAccess_FileRename $existingFilepath $newFilepath]

Renames a file from existingFilepath to newFilepath.

Returns 1 for success, 0 for failure.

# offset is an integer
# origin is an integer
set status [CkFileAccess_FileSeek $offset $origin]

Sets the file pointer for the currently open file. The offset is an offset in bytes from the origin. The origin can be one of the following:

0 = Offset is from beginning of file.
1 = Offset is from current position of file pointer.
2 = Offset is from the end-of-file (offset may be negative).

Returns 1 for success, 0 for failure.

# filePath is a string
set status [CkFileAccess_FileSize $filePath]

Returns the size, in bytes, of a file. Returns -1 for failure.

Returns 1 for success, 0 for failure.

# data is a CkByteData
set status [CkFileAccess_FileWrite $data]

Writes bytes to the currently open file.

Returns 1 for success, 0 for failure.

# binData is a CkBinData
# offset is an integer
# numBytes is an integer
set status [CkFileAccess_FileWriteBd $binData $offset $numBytes]

Introduced in version 9.5.0.64

Writes the contents of binData to the currently open file. To specify the entire contents of binData, set both offset and numBytes equal to 0. To write all remaining data starting at offset, then set numBytes equal to 0.

Returns 1 for success, 0 for failure.

Unzip Binary File to Stream

# index is an integer
# length is an integer
# encoding is a string
# outStr is a CkString (output)
set status [CkFileAccess_GenBlockId $index $length $encoding $outStr]
set retStr [CkFileAccess_genBlockId $myFileAccess $index $length $encoding]

Introduced in version 9.5.0.58

This is purely a utility/convenience method -- initially created to help with block file uploads to Azure Blob storage. It generates a block ID string that is the decimal representation of the index in length chars, and then encoded according to encoding (which can be an encoding such as "base64", "hex", "ascii", etc.) For example, if index = 8, length = 12, and encoding = "base64", then the string "00000012" is returned base64 encoded.

Returns 1 for success, 0 for failure.

# path is a string
# outStr is a CkString (output)
set status [CkFileAccess_GetDirectoryName $path $outStr]
set retStr [CkFileAccess_getDirectoryName $myFileAccess $path]

Introduced in version 9.5.0.64

Returns the directory information for the specified path string.

GetDirectoryName('C:\MyDir\MySubDir\myfile.ext') returns 'C:\MyDir\MySubDir\'
GetDirectoryName('C:\MyDir\MySubDir') returns 'C:\MyDir\'
GetDirectoryName('C:\MyDir\') returns 'C:\MyDir\'
GetDirectoryName('C:\MyDir') returns 'C:\'
GetDirectoryName('C:\') returns 'C:\'

Returns 1 for success, 0 for failure.

Demonstrate Directory Path Functions

# path is a string
# outStr is a CkString (output)
set status [CkFileAccess_GetExtension $path $outStr]
set retStr [CkFileAccess_getExtension $myFileAccess $path]

Introduced in version 9.5.0.64

Returns the extension of the specified path string.

GetExtension('C:\mydir.old\myfile.ext') returns '.ext'
GetExtension('C:\mydir.old\') returns ''

Returns 1 for success, 0 for failure.

Demonstrate Directory Path Functions

# path is a string
# outStr is a CkString (output)
set status [CkFileAccess_GetFileName $path $outStr]
set retStr [CkFileAccess_getFileName $myFileAccess $path]

Introduced in version 9.5.0.64

Returns the file name and extension of the specified path string.

GetFileName('C:\mydir\myfile.ext') returns 'myfile.ext'
GetFileName('C:\mydir\') returns ''

Returns 1 for success, 0 for failure.

Demonstrate Directory Path Functions

# path is a string
# outStr is a CkString (output)
set status [CkFileAccess_GetFileNameWithoutExtension $path $outStr]
set retStr [CkFileAccess_getFileNameWithoutExtension $myFileAccess $path]

Introduced in version 9.5.0.64

Returns the file name of the specified path string without the extension.

GetFileNameWithoutExtension('C:\mydir\myfile.ext') returns 'myfile'
GetFileNameWithoutExtension('C:\mydir\') returns ''

Returns 1 for success, 0 for failure.

Demonstrate Directory Path Functions

# returns a CkDateTime
# path is a string
# which is an integer
set ret_ckDateTime [CkFileAccess_GetFileTime $path $which]

Introduced in version 9.5.0.71

Gets one of the following date/times for a file:

0: Last-modified
1: Last-access
2: Creation
The "path" argument indicates which time to return. The values can be 0, 1, or 2.

Note: Linux filesystems do not keep a file's creation date/time. In such a case, this method will return the last-modified time.

Returns NULL on failure

# returns a CkDateTime
# path is a string
set ret_ckDateTime [CkFileAccess_GetLastModified $path]

Introduced in version 9.5.0.66

Gets the last-modified date/time for a file.

Returns NULL on failure

# blockSize is an integer
set retInt [CkFileAccess_GetNumBlocks $blockSize]

Introduced in version 9.5.0.58

Returns the number of blocks in the currently open file. The number of bytes per block is specified by blockSize. The number of blocks is the file size divided by the blockSize, plus 1 if the file size is not evenly divisible by blockSize. For example, if the currently open file is 60500 bytes, and if the blockSize is 1000 bytes, then this method returns a count of 61 blocks.

Returns -1 if no file is open. Return 0 if the file is completely empty (0 bytes).

File Read Blocks

# dirPath is a string
# prefix is a string
# outStr is a CkString (output)
set status [CkFileAccess_GetTempFilename $dirPath $prefix $outStr]
set retStr [CkFileAccess_getTempFilename $myFileAccess $dirPath $prefix]

Creates a temporary filepath of the form dirPath\prefix_xxxx.TMP Where "xxxx" are random alpha-numeric chars. The returned filepath is guaranteed to not already exist.

Returns 1 for success, 0 for failure.

# filePath is a string
set status [CkFileAccess_OpenForAppend $filePath]

Opens a file for appending. If filePath did not already exists, it is created. When an existing file is opened with this method, the contents will not be overwritten and the file pointer is positioned at the end of the file.

If the open/create failed, then error information will be available in the FileOpenError and FileOpenErrorMsg properties.

Returns 1 for success, 0 for failure.

# filePath is a string
set status [CkFileAccess_OpenForRead $filePath]

Opens a file for reading. The file may contain any type of data (binary or text) and it must already exist. If the open failed, then error information will be available in the FileOpenError and FileOpenErrorMsg properties.

Returns 1 for success, 0 for failure.

# filePath is a string
set status [CkFileAccess_OpenForReadWrite $filePath]

Opens a file for reading/writing. If filePath did not already exists, it is created. When an existing file is opened with this method, the contents will not be overwritten, but the file pointer is positioned at the beginning of the file.

If the open/create failed, then error information will be available in the FileOpenError and FileOpenErrorMsg properties.

Returns 1 for success, 0 for failure.

# filePath is a string
set status [CkFileAccess_OpenForWrite $filePath]

Opens a file for writing. If filePath did not already exists, it is created. When an existing file is opened with this method, the contents will be overwritten. (For example, calling OpenForWrite on an existing file and then immediately closing the file will result in an empty file.) If the open/create failed, then error information will be available in the FileOpenError and FileOpenErrorMsg properties.

Returns 1 for success, 0 for failure.

# filePath is a string
# encoding is a string
# outStr is a CkString (output)
set status [CkFileAccess_ReadBinaryToEncoded $filePath $encoding $outStr]
set retStr [CkFileAccess_readBinaryToEncoded $myFileAccess $filePath $encoding]

Reads the entire contents of a binary file and returns it as an encoded string (using an encoding such as Base64, Hex, etc.) The encoding may be one of the following strings: base64, hex, qp, or url.

Returns 1 for success, 0 for failure.

Base64 Encode a File

# blockIndex is an integer
# blockSize is an integer
# outBytes is a CkByteData (output)
set status [CkFileAccess_ReadBlock $blockIndex $blockSize $outData]

Introduced in version 9.5.0.58

Reads the Nth block of a file, where the size of each block is specified by blockSize. The first block is at blockIndex 0. If the block to be read is the last in the file and there is not enough data to fill an entire block, then the partial block is returned.

Returns 1 for success, 0 for failure.

File Read Blocks

# filePath is a string
# outBytes is a CkByteData (output)
set status [CkFileAccess_ReadEntireFile $filePath $outData]

Reads the entire contents of a binary file and returns the data.

Returns 1 for success, 0 for failure.

# filePath is a string
# charset is a string
# outStrFileContents is a CkString (output)
set status [CkFileAccess_ReadEntireTextFile $filePath $charset $outStr]
set retStr [CkFileAccess_readEntireTextFile $myFileAccess $filePath $charset]

Reads the entire contents of a text file, interprets the bytes according to the character encoding specified by charset, and returns the text file as a string.

Returns 1 for success, 0 for failure.

# partsDirPath is a string
# partPrefix is a string
# partExtension is a string
# reassembledFilename is a string
set status [CkFileAccess_ReassembleFile $partsDirPath $partPrefix $partExtension $reassembledFilename]

Reassembles a file previously split by the SplitFile method.

Returns 1 for success, 0 for failure.

Example: Reassemble a Previously Split File

# filePath is a string
# charset is a string
# existingString is a string
# replacementString is a string
set retInt [CkFileAccess_ReplaceStrings $filePath $charset $existingString $replacementString]

Replaces all occurrences of existingString with replacementString in a file. The character encoding, such as utf-8, ansi, etc. is specified by charset.

# path is a string
set status [CkFileAccess_SaveLastError $path]

Saves the last-error information (the contents of LastErrorXml) to an XML formatted file.

Returns 1 for success, 0 for failure.

# dirPath is a string
set status [CkFileAccess_SetCurrentDir $dirPath]

Sets the current working directory for the calling process to dirPath.

Returns 1 for success, 0 for failure.

# filePath is a string
# createTime is a CkDateTime
# lastAccessTime is a CkDateTime
# lastModTime is a CkDateTime
set retBool [CkFileAccess_SetFileTimes $filePath $createTime $lastAccessTime $lastModTime]

Sets the create date/time, the last-access date/time, and the last-modified date/time for a file. For non-Windows filesystems where create times are not implemented, the createTime is ignored.

# filePath is a string
# lastModified is a CkDateTime
set retBool [CkFileAccess_SetLastModified $filePath $lastModified]

Sets the last-modified date/time for a file.

# fileToSplit is a string
# partPrefix is a string
# partExtension is a string
# partSize is an integer
# destDir is a string
set status [CkFileAccess_SplitFile $fileToSplit $partPrefix $partExtension $partSize $destDir]

Splits a file into chunks. Please refer to the example below:

Returns 1 for success, 0 for failure.

Example: Split File into Chunks

# path is a string
set status [CkFileAccess_TreeDelete $path]

Deletes an entire directory tree (all files and sub-directories).

Returns 1 for success, 0 for failure.

# filePath is a string
# fileData is a CkByteData
set status [CkFileAccess_WriteEntireFile $filePath $fileData]

Opens/creates filePath, writes fileData, and closes the file.

Returns 1 for success, 0 for failure.

# filePath is a string
# textData is a string
# charset is a string
# includedPreamble is a boolean
set status [CkFileAccess_WriteEntireTextFile $filePath $textData $charset $includedPreamble]

Opens filePath, writes textData using the character encoding specified by charset, and closes the file. If includedPreamble is 1 and the charset is Unicode or utf-8, then the BOM is included at the beginning of the file.

Returns 1 for success, 0 for failure.

Base64 Encode a File