Windows File operation API

Source: Internet
Author: User
Tags filetime readfile

The following are the APIs for file operations in windows and their functions:
Windows API functions
Closehandle closes a kernel object. This includes file, file ing, process, thread, security, and synchronization objects. When file processing is involved, this function is usually similar to the close command of VB. Close should be used whenever possible because it supports VB error control. Note that the file handle used by this function is different from the file number of VB.
Comparefiletime: Compare the time of the two files based on the filetime structure information.
Copyfile: copy the file. Similar to the filecopy command of VB
Createfile is a full-featured function that allows you to open and create files, pipelines, mail slots, communication services, devices, and the console.
Deletefile: delete a specified file
Findclose closes a search handle created by the findfirstfile function.
Findfirstfile
Findnextfile searches for the next file based on a file name specified when the findfirstfile function is called.
Flushfilebuffers refreshes the internal file buffer for the specified file handle
Getbinarytype determines whether the file can be executed
Getfileattributes determines the attributes of a specified file
The getfileinformationbyhandle function provides a mechanism for obtaining file information-loading file-related information in a by_handle_file_information structure.
Getfilesize determines the file length
Getfiletime: Get the time information of the specified object
Getfiletype: determines the file type while giving the file handle.
Getfileversioninfo obtains the file version information from a module that supports version tagging.
Getfileversioninfosize determines the size of a buffer zone for a file containing version Resources
Getshortpathname: Get the short path name of the specified file
The gettempfilename function contains the name of a temporary file, which can be used by applications.
Lclose to close the specified file. Refer to the closehandle function for more information.
Lcreat creates a file. If the file already exists, it will be shortened to zero length and opened for read/write
Llseek sets the current position for reading and writing in the file. This function is similar to the seek Statement of VB. If you use the open command of VB to open a file, do not use the llseek function for this file.
Lockfile is available in Shared Mode in windows. In this case, multiple processes can access the file at the same time. With this function, an application that reads and writes a file can lock a part of the file so that it cannot be accessed by other applications. This avoids conflicts during simultaneous read/write operations.
Lockfileex is similar to lockfile, but it provides more functions.
Lopen opens the specified file in binary mode.
Lread reads data from files into the memory buffer.
Lwrite writes data from the memory buffer to a file
Movefile and movefileex move the file. If dwflags is set to zero, movefile is equivalent to movefileex.
The openfile function can perform a large number of different file operations. Compared with this function, consider the Win32 createfile function (it can open the named pipeline and control the Unicode file name without the limit of the path name with 128 characters)
Readfile reads data from the file. Compared with the lread function, this function is much more flexible. This function can be used to operate communication devices, pipelines, sockets, and mail slots.
Readfileex is similar to readfile, but it can only be used for asynchronous read operations and contains a complete callback.
Searchpath
Setendoffile sets the current file location to the end of the file for an opened file
Setfileattributes
Setfilepointer sets the current read/write location in a file
Setfiletime: Set the file creation, access, and last modification time.
Unlockfile unlocks a file
Unlockfileex unlocks a file
Writefile writes data to a file. This function is more flexible than the lwrite function. This function can also be used to process communication devices, pipelines, sockets, and mail slots.
Writefileex is similar to writefile, but it can only be used for asynchronous write operations and includes a complete callback.

Let's take a look at the main functions and their usage through several examples:
1. createfile
Role: This is a full-featured routine that allows you to open and create files, pipelines, mail slots, communication services, devices, and the console.
Declaration Form:
Declare function createfile lib "Kernel32" alias "createfilea" (byval lpfilename as string, byval dwdesiredaccess as long, byval dw1_mode as long, lpsecurityattributes as security_attributes, byval dwcreationdisposition as long, byval dwflagsandattributes as long, byval htemplatefile as long) as long
Note:
The Return Value Type of this function is long. If the execution is successful, the file handle is returned. Invalid_handle_value indicates an error and getlasterror is set. Even if the function succeeds, if the file exists and create_always or open_always are specified, getlasterror is set to error_already_exists.
When you open a communication port (such as COM1), you must set it to open_existing in any case.
This function replaces lopen and lcreate functions and should be our first choice.
Parameter description:
Parameter type and description
Lpfilename string, name of the file to be opened
Dwdesiredaccess long. If generic_read is used, read access to the device is allowed. If generic_write is used, write access to the device is allowed (can be used in combination). If it is set to zero, indicates that only information related to one device can be obtained.
Dww.mode long, zero indicates that the file is not shared; file_1__read and/or file_1__write indicates that shared access to the file is allowed.
Lpsecurityattributes security_attributes, pointing to a security_attributes structure pointer, defines the file security features (if supported by the operating system)
Dwcreationdisposition long, one of the following constants:
Create_new: Creates a file. If the file exists, an error occurs.
Create_always: Creates a file and changes the previous file.
The open_existing file must already exist. Requirements from devices
Open_always: Create an open_always file if it does not exist.
Truncate_existing indicates that the existing file is shortened to zero length.
Dwflagsandattributes long, one or more of the following Constants
File_attribute_archive mark archive attributes
File_attribute_compressed marks the file as compressed, or marks it as the default compression mode of the file in the directory.
File_attribute_normal default attribute
File_attribute_hidden: hide a file or directory
The file_attribute_readonly file is read-only.
The file_attribute_system file is a system file.
The file_flag_write_through operating system must not postpone file write operations.
File_flag_overlapped allows overlapping operations on files
File_flag_no_buffering prohibits file caching. The file can only be written into the Sector blocks of the disk volume.
File_flag_random_access optimizes the File Buffer for Random Access
File_flag_sequential_scan optimizes the File Buffer for continuous access
File_flag_delete_on_close closes the last opened handle and deletes the file. Especially suitable for temporary files
You can also combine the following constant tags in Windows NT:
Security_anonymous, security_identification, security_impersonation, security_delegation, security_context_tracking, security_inclutive_only
Htemplatefile long. If it is not zero, a file handle is specified. The new file will copy the extended attributes from this file.

Example:
Long hfile = createfile ("C: // test.txt", generic_read,
File_cmd_read | file_cmd_write, null,
Open_existing, file_elag_overlapped, null)

 

2. lcreat
Purpose: create a file. If the file already exists, it will be shortened to zero length and opened for read/write
Declaration Form:
Declare function lcreat lib "Kernel32" alias "_ lcreat" (byval lppathname as string, byval iattribute as long) as long
Description: The Return Value Type of this function is long. If the execution is successful, a handle to open the file is returned. If an error occurs, hfile_error is returned.
This function will open files opened by other applications, so be careful when using it. The createfile function of Win32 has replaced this function. This function works the same as the open statement of VB.
Parameter description:
Parameter type and description
Lppathname string, name of the file to be created
Iattribute long, one of the following values:
0 -- the file can be read and written
1 -- create a read-only file
2 -- create a hidden file
3 -- create a system file
For example, the following statement opens the C:/test.txt file.
Lcreat "C:/test.txt", 0

3. lopen
Purpose: open a specified file in binary mode.
Declaration Form:
Declare function lopen lib "Kernel32" alias "_ lopen" (byval lppathname as string, byval ireadwrite as long) as long
Description: The Return Value Type of this function is long. If the execution is successful, a handle to open the file is returned. Hfile_error indicates an error. Getlasterror is set.
The createfile function provides more functions under Win32:
Parameter description:
Parameter type and description
Lppathname string, name of the file to be opened
Ireadwrite long, a combination of the access mode and the shared mode constant, as shown below:
1. Access Mode
Read: open the file and read the content.
Read_write open the file and read and write it
Write: open the file and write the content in it.
2. Sharing Mode (refer to the mark constant table of the openfile function)
Of_share_compat, of_share_deny_none, of_share_deny_read, of_share_deny_write, of_share_exclusive
  

4. getfiletime
Purpose: Obtain the time information of the specified file.
Declaration Form:
Declare function getfiletime lib "Kernel32" alias "getfiletime" (byval hfile as long, lpcreationtime as filetime, lplastaccesstime as filetime, lplastwritetime as filetime) as long
Note: Long, non-zero indicates successful, and zero indicates failed. Getlasterror is set.
If you do not need specific information, you can set the value of lpcreationtime, lplastaccesstime, and lplastwritetime to zero (byval as long ). The file time returned by this function is in UTC format.
Parameter description:
Parameter type and description
Hfile long, file handle
Lpcreationtime filetime, used to load the File Creation Time
Lplastaccesstime filetime, used to load the last file access time (this feature is not supported by the FAT file system)
Lplastwritetime filetime, used to load the last modification time of the file
The sample code is as follows:
'Function Declaration
Private declare function getfiletime lib "Kernel32" (byval hfile as long, lpcreationtime as filetime, lplastaccesstime as filetime, lplastwritetime as filetime) as long
Private declare function lopen lib "Kernel32" alias "_ lopen" (byval lppathname as string, byval ireadwrite as long) as long
'Define variables
Dim file as long
Dim creationtime as filetime
Dim lastaccesstime as filetime
Dim lastaccesstime as filetime
'Define the structure
Private type filetime
Dwlowdatetime as long
Dwhighdatetime as long

End type
Private sub form_load ()
Str1 = "C:/text.txt"
File = lopen (str1, read_write) 'open the file
Temp = getfiletime (file, creationtime, lastaccesstime, lastwritetime )'
Msgbox creationtime' display information
End sub
The code above shows the File Creation Time

 

5. copyfile
Purpose: copy an object. Similar to the filecopy command of VB
Declaration Form:
Declare function copyfile lib "Kernel32" alias "copyfilea" (byval lpexistingfilename as string, byval lpnewfilename as string, byval bfailifexists as long) as long
Note: Long, non-zero indicates successful, and zero indicates failed. Getlasterror is set.
Parameter description:
Parameter type and description
Lpexistingfilename string, source file name
Lpnewfilename string, target file name
Bfailifexists long. If it is set to true (non-zero), function call fails once the target file already exists. Otherwise, the target file is rewritten.
The sample code is as follows:
'Function Declaration
Private declare function copyfile lib "Kernel32" alias "copyfilea" (byval lpexistingfilename as string, byval lpnewfilename as string, byval bfailifexists as long) aslong
Private sub form_load ()
Copyfile "C:/test1.txt", "C:/test2.txt", 1
End sub
The above code copies C:/test1.txt to C:/test2.txt

 

6. movefile and movefileex
Function: Move a file. If dwflags is set to zero, movefile is equivalent to movefileex.
Declaration Form:
Declare function movefile & lib "Kernel32" alias "movefilea" (byval lpexistingfilename as string, byval lpnewfilename as string)
Declare function movefileex & lib "Kernel32" alias "movefileexa" (byval lpexistingfilename as string, byval lpnewfilename as string, byval dwflags as long)
Note: Long, non-zero indicates successful, and zero indicates failed. Getlasterror is set.
These two functions generally cannot move files from one volume to another. If the movefile_copy_allowed flag is set, movefileex can do this.
Parameter description:
Parameter type and description
Lpexistingfilename string, name of the file to be moved
Lpnewfilename string, new file name
Dwflags long, one or more of the following Constants
Movefile_replace_existing Replace the target file if it exists.
If movefile_copy_allowed is moved to a different volume, copy the file and delete the original file.
The movefile_delay_until_reboot mobile operation is officially started the next time the system restarts. In this way, you can change the system file in Windows NT
The sample code is as follows:
'Define the structure
Private const movefile_copy_allowed = & H2
Private const movefile_delay_until_reboot = & h4
Private const movefile_replace_existing = & H1
'Function Declaration
Private declare function movefile & lib "Kernel32" alias "movefilea" (byval lpexistingfilename as string, byval lpnewfilename as string)
Private declare function movefileex & lib "Kernel32" alias "movefileexa" (byval lpexistingfilename as string, byval lpnewfilename as string, byval dwflags as long)
Private sub form_load ()
Movefile "C:/test.txt", "d:/test1.txt" 'Move the file
Movefileex "D:/test1.txt", "C:/test.txt", movefile_replace_existing 'Move again
End sub
The above code moves the file. After two moves, the file remains unchanged.

 

7. deletefile
Purpose: delete a specified file.
Declaration Form:
Declare function deletefile lib "Kernel32" alias "deletefilea" (byval lpfilename as string) as long
Note: Long, non-zero indicates successful, and zero indicates failed. Getlasterror is set.
Similar to the kill Statement of VB, be careful when using this function in Windows 95-this function will delete a file even if it is being opened by an application.
Parameter description:
Parameter type and description
Lpfilename string, name of the object to be deleted
The sample code is as follows:
'Function Declaration
Private declare function deletefile lib "Kernel32" alias "deletefilea" (byval lpfilenameas string) as long
Private sub form_load ()
Deletefile "C:/test.txt"
End sub
The above code deletes the C:/test.txt file.
Although VB is a rad tool, and many people do not want to use it, it is realistic to say that VB is indeed powerful, especially the user-friendly design.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.