Windows File OperationsBasic Code
A basic code file. h for file operations in Windows is defined as the file class:
# Pragma once
# Include <windows. h>
# Include <assert. h>
Class File
{
Handle hfile; // file handle
Public:
Void open (lpcwstr filename );
Int read (char * data, int Len );
Void movefp (long disp, int type );
Int write (char * data, int Len );
Void close ();
Static void copy (lpcwstr SRC, lpcwstr des );
Static void move (lpcwstr SRC, lpcwstr des );
Static void del (lpcwstr name );
};
The file class is implemented as follows:
1. Open a file: The file is opened in read/write mode, and is created if the file does not exist.
Void file: open (lpcwstr filename)
{
// Use creatfile to open a file in read/write mode
Hfile = createfile (filename, // file name
Generic_write | generic_read, // read/write permission
File_cmd_read | file_cmd_write // share the read/write permission
, Null // security features
, Open_always // create_new-there is an error, create_always-there is a file to rewrite, open_existing-there is no error, open_always-there is no creation
// Truncate_existing-shorten the existing file length to 0
, File_attribute_normal // file_attribute ^ X, x_archive-mark archiving, x_normal-default, x_hidden-hide, x_readonly-read-only, x_system-System
, Null );
Assert (hfile! = Invalid_handle_value );
}
2. close the file:
Void file: Close ()
{
Closehandle (hfile );
}
3. Read files:
Int file: Read (char * data, int Len)
{
DWORD dwwrite;
Bool rslt = readfile (hfile, Data, Len, & dwwrite, null );
Assert (rslt );
Return dwwrite;
}
4. Write files:
Int file: Write (char * data, int Len)
{
DWORD dwwrite;
Bool rslt = writefile (hfile, Data, Len, & dwwrite, null );
Assert (rslt );
Return dwwrite;
}
5. Move the file pointer:
Void file: movefp (long disp, int type)
{
Setfilepointer (hfile, DISP, null, type );
}
6. Other File Operation APIs: Copy, move, and delete (Scalable ):
Void file: Copy (lpcwstr SRC, lpcwstr des)
{
Assert (copyfile (SRC, Des, true ));
}
Void file: Move (lpcwstr SRC, lpcwstr des)
{
Assert (movefile (SRC, des ));
}
Void file: del (lpcwstr name)
{
Assert (deletefile (name ));
}