Attached is my attempt to use File API to read and write binary files. Like the VB6 FreeFile command, it uses GetFNum to find the first available file structure defined as an array of:
Code:
Private Type FileStruct
FileName As Long
FileHndl As Long
FileLen As Long
End Type
The size of the array is defined by MaxFiles, and the FileName is stored as a long pointer to an associated string array containing the actual file names. This was done to maximize speed by maintaining fixed length User Defined Types. For the same reason, fixed length buffers were also used along with the length to prevent memory having to be reassigned with changes in length. Instead of accessing file data by number, file handles are used instead. Clearing the FileHndl enables the UDT to be reused without having to clear the 2 other variables.
When opening a file for write, the routine recognizes that a file by the chosen name may already exist. If it does, it prompts you to overwrite it much like the Command Line copy command. Choosing to overwrite it truncates the file size before writing.
In this demo, the default write directory is the current operating directory. A short demo file (kitty.htm) is also included.
J.A. Coutts
Updated: See post #4 for details
Last edited by couttsj; Jul 20th, 2024 at 11:56 AM.
Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.
You may want to change that FileLen to a Currency, as much of the reason people do API file I/O is to handle very large files.
If someone needs to work with very large files, I am sure the program can be adjusted to suit. I was more interested in speed. During my work with IOCP, I learned that fixed length buffers are very important in achieving speed. The best buffer length to use is dependant on the application. In general, the bigger the file, the bigger the buffer. But that has to be balanced against additional processing requirements such as encryption or network speed. There is no single best fit.
The Open, Read, Write, and Close functions have been moved to a Module to make the routines more reusable. It must be initialized and I have used Sub Main in this particular example. There is no need to find an available file number, as the file number (starting at 0) will be returned when the file is opened.