Author: risingmine Article Source: Tianji development clicks: 4487 updated: 17:07:51
In VC programming Composition There are two main methods: The cfile class using API functions and MFC. Microsoft encapsulates the general operations on files. The following describes how to use these two methods to perform file operations.
1. Create or open a file
The API function createfile can be used to open and create files, pipelines, mail slots, communication services, devices, and the console. However, this function only describes how to create and open a file.
Handle createfile (
Lptstr lpfilename, // name of the file to be opened
DWORD dwdesiredaccess, // file operation attributes
DWORD dw1_mode, // file sharing attribute
Lpsecurity_attributes lpsecurityattributes, // file security features
DWORD dwcreationdisposition, // File Operations
DWORD dwflagsandattributes, // file attributes
Handle htemplatefile // if it is not zero, a file handle is specified. The new file will copy the extended attributes from this file.
);
File Operation attribute: If it is zero, only information related to one device can be obtained, and generic_read indicates that read access is allowed to the device; if generic_write is used, write access to the device is allowed (can be used in combination );
File Sharing property: zero indicates that the file is not shared; file_1__read or file_1__write indicates that shared access to the file is allowed;
File Operations include:
• Create_new: create a file. If the file exists, an error occurs.
• Create_always: create a file and rewrite the previous file.
• Open_existing: the file must already exist. Requirements from devices
• Open_always: create a file if the file does not exist.
• Truncate_existing: shorten the existing file to zero length
File attributes include:
• File_attribute_archive: Mark archive attributes
• File_attribute_compressed: Mark the file as compressed, or mark it as the default compression mode of the file in the directory
• File_attribute_normal: Default attribute
• File_attribute_hidden: hides files or directories.
• File_attribute_readonly: The file is read-only.
• File_attribute_system: The file is a system file.
• File_flag_write_through: the operating system shall not delay file write operations.
• File_flag_overlapped: Allows overlapping operations on files.
• File_flag_no_buffering: file buffering is prohibited. 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 file buffering for continuous access
• File_flag_delete_on_close: After closing the last opened handle, delete the file. Especially suitable for temporary files
Attributes that can be combined include: file_flag_write_through, file_flag_overlapped,
File_flag_no_buffering, file_flag_random_access,
File_flag_sequential_scan, file_flag_delete_on_close,
File_flag_backup_semantics, file_flag_posix_semantics,
File_flag_open_reparse_point, file_flag_open_no_recall
If the call succeeds, a dozen
Open the file handle. If the file exists before calling the function, the file operation attribute is: create_always or
Open_always: Use the getlasterror function to return error_already_exists (including the successful function operation). If the previous function does not exist
In, 0 is returned. If the usage fails, invalid_handle_value is returned. To obtain more information, use the getlasterror function.
Close file:
Bool closehandle (handle hobject // handle to object to close );
Example 1: create a file under the current directory:
Handle handle;
DWORD num;
Handle =: createfile ("New. tmp", generic_read | generic_write, 0, null, open_always, file_flag_delete_on_close, null );
If (invalid_handle_value! = Handle)
{
: Setfilepointer (handle, 0, 0, file_begin );
Char buffer [] = "this is a newly created file ";
: Writefile (handle, buffer, sizeof (buffer), & num, null );
Zeromemory (buffer, sizeof (buffer ));
: Setfilepointer (handle, 0, 0, file_begin );
: Readfile (handle, buffer, sizeof (buffer), & num, null );
MessageBox (buffer );
: Closehandle (handle );
}
You can change the attributes and operations of the created file to see different results.
Cfile creates and opens a file:
There are many ways to create and open files. The following describes several constructors:
Cfile (lpctstr lpszfilename, uint nopenflags );
Throw (cfileexception );
Cfile ();
Bool open (lpctstr lpszfilename, uint nopenflags, cfileexception * perror = NULL );
Lpszfilename: file name, which can be a relative path, absolute path, or network path
Nopenflags: open in the following ways:
• Cfile: modecreate calls the constructor to construct a new file. If the file already exists, the length is changed to 0.
• Cfile: modenotruncate this value is used in combination with modecreate. If the created file already exists, its length cannot be changed to 0. Therefore, this file is opened, either as a new file or as an existing file. This is useful, for example, when opening a file that may or may not exist.
• Cfile: The file opened by moderead is only for reading.
• Cfile: modereadwrite open the file for reading and writing.
• Cfile: modewrite: open the file for writing only.
• Cfile: modenoinherit blocks file quilt process inheritance.
• Cfile: sharedenynone does not prohibit other processes from reading or writing access and opens the file. If the file has been opened by other processes in compatible mode, the create operation fails.
• Cfile: sharedenyread: open the file and prohibit other processes from reading the file. If the file has been opened by another process in compatibility mode or is read by another process, create fails.
• Cfile: sharedenywrite: open the file and prohibit other processes from writing this file. If the file has been opened by another process in compatible mode or written by another process, create fails.
• Cfile: The volume exclusive mode is used to open the file and prohibit other processes from reading and writing the file. If the file has been opened for read/write in another mode (even by the current process), the structure fails.
• Cfile: Invalid compat. This flag is invalid in 32-bit MFC. This flag maps to cfile: Export exclusive when cfile: open is used.
• Cfile: typetext sets special processes for line breaks (for derived classes only ).
• Cfile: typebinary sets the binary mode (for derived classes only ).
The following is an example in msdn:
Char * pfilename = "test. dat ";
Try
{
Cfile F (pfilename, cfile: modecreate | cfile: modewrite );
}
Catch (cfileexception, E)
{
# Ifdef _ debug
Afxdump <"file cocould not be opened" <e-> m_cause <"\ n ";
# Endif
}
End_catch
Cfile filetest;
Char * pfilename = "test. dat ";
Try
{
Filetest. Open (pfilename, cfile: modecreate | cfile: modewrite );
}
Catch_all (E)
{
Filetest. Abort ();
Throw_last ();
}
End_catch_all
2. file read/write Positioning
It is very important to locate the data in the file, which determines the location of the written data in the file. API functions
DWORD setfilepointer (
Handle hfile, // file handle
Long ldistancetomove, // byte offset R
Plong lpdistancetomovehigh, // specify a long integer variable, which contains a high dual-word offset to be used (usually used to operate large files ). It can be set to zero, indicating that only ldistancetomove is used.
DWORD dwmovemethod // File Location
);
There are three methods to locate the dwmovemethod file:
• File_begin: Starting from the file.
• File_current: from the current location.
• File_end: from the end of the file.
This function can be used to locate large files. lpdistancetomovehigh is a 32-bit high and ldistancetomove is a 32-bit low. If
When lpdistancetomovehigh is null, the function operation is successful and the offset of the data in the current file is returned. If lpdistancetomovehigh is not
If it is null, the 32-bit offset of the returned data is placed in lpdistancetomovehigh. If the function call fails, 0xffffffff is returned.
Bool setendoffile (handle hfile // file handle );
The file data locating functions of the cfile class include:
Long seek (long Loff, uint nfrom );
Throw (cfileexception );
If the requested location is valid, seek returns the new byte offset starting from the file.
Loff: the number of bytes that the pointer moves.
Nfrom: pointer movement mode. It can be cfile: Begin, cfile: Current, cfile: End
Void seektobegin ();
DWORD seektoend (); // The length of the returned file (in bytes ).
The following is an example of reading information from a bitmap file:
Cfile file;
Bitmapinfoheader BMP Info;
Try
{
File. Open ("d :\\ toolbar.bmp", cfile: moderead );
File. Seek (sizeof (bitmapfileheader), cfile: Begin );
File. Read (& BMP info, sizeof (bitmapinfoheader ));
Cstring STR;
Str. Format ("the length of the bitmap file is % d, height % d", BMP info. biwidth, BMP info. biheight );
MessageBox (STR );
File. Close ();
}
Catch (cfileexception * E)
{
Cstring STR;
Str. Format ("failed to read data: % d", e-> m_cause );
MessageBox ("str ");
File. Abort ();
E-> Delete ();
}
Read data:
Bool readfile (
Handle hfile, // file handle
Lpvoid lpbuffer, // a buffer used to save read data
DWORD nnumberofbytestoread, // number of characters to read
Lpdword lpnumberofbytesread, // number of characters actually read from the file
Lpoverlapped // If file_flag_overlapped is specified when the file is opened, a special structure must be referenced using this parameter. This structure defines an asynchronous read operation. Otherwise, set this parameter to null.
);
Cfile member functions include:
Uint read (void * lpbuf, uint ncount );
Throw (cfileexception); // The returned value is the number of bytes transmitted to the buffer.
Write Data:
Bool writefile (
Handle hfile, // file handle
Lpvoid lpbuffer, // a data buffer to be written
DWORD nnumberofbytestowrite, // number of bytes to write data. If the value is written to zero byte, it indicates that nothing is written, but the "last modification time" of the file is updated ".
Lpdword lpnumberofbyteswritten, // number of bytes actually written to the file
Lpoverlapped // overlapped. If a file is opened on the premise of file_flag_overlapped, this parameter must reference a special structure. This structure defines an asynchronous write operation. Otherwise, this parameter should be set to null.
);
Void write (const void * lpbuf, uint ncount );
Throw (cfileexception );
Lpbuf: point to the buffer provided by the user, including data that will be written into the file
Ncount: the number of bytes transmitted from the buffer zone. For text files, press enter to wrap the line as a character.
The following is an example of writing data into a file:
Cfile file;
Try
{
File. Open ("D:/My. dat", cfile: modecreate | cfile: modewrite );
File. seektobegin ();
Char data [] = "111111111 \ n1111111111 ";
File. Write (data, sizeof (data ));
File. Flush ();
File. Close ();
}
Catch (cfileexception * E)
{
Cstring STR;
Str. Format ("failed to read data: % d", e-> m_cause );
MessageBox ("str ");
File. Abort ();
E-> Delete ();
}
3. Obtain and set the file creation time, last access time, and last write time.
Bool getfiletime (
Handle hfile, // file handle
Lpfiletime lpcreationtime, // Creation Time
Lpfiletime lplastaccesstime, // last access time
Lpfiletime lplastwritetime // The last write time
);
Bool setfiletime (
Handle hfile,
Const filetime * lpcreationtime,
Const filetime * lplastaccesstime,
Const filetime * lplastwritetime
);
Typedef struct _ filetime {
DWORD dwlowdatetime;
DWORD dwhighdatetime;
} Filetime;
The obtained three parameters are in the filetime structure and get the UTC time. You can use the API function filetimetolocalfiletime () and
Filetimetosystemtime () converts them to the local time and system time format. You can also use localfiletimetofiletime
And systemtimetofiletime (), and set the file creation time, last access time, and last write time through setfiletime. Because you need
Open the file first, and the last access time obtained is the current time, which is meaningless and troublesome. The static method in the cfile class is described below.
Static bool Pascal getstatus (lpctstr lpszfilename, cfilestatus & rstatus );
Static void setstatus (lpctstr lpszfilename, const cfilestatus & status );
Throw (cfileexception );
The returned result is a cfilestatus object. The specific member variables of this structure include:
Struct cfilestatus
{
Ctime m_ctime; // File Creation Time
Ctime m_mtime; // last file modification time
Ctime m_atime; // last file access time
Long m_size; // File Size
Byte m_attribute; // file attributes
Byte _ m_padding; // no actual meaning, used to add a byte
Tchar m_szfullname [_ max_path]; // absolute path
# Ifdef _ debug
// Implement the dump virtual function and output file attributes
Void dump (cdumpcontext & DC) const;
# Endif
};
The following is an example:
Cfilestatus status;
Char * Path = "D: \ VSS ";
If (cfile: getstatus (path, status ))
{
Cstring ctime, mtime, atime;
Ctime = status. m_ctime.format ("File Creation Time: % Y year % m month % dday % H % m minute % s second ");
Mtime = status. m_mtime.format ("Last file modification time: % Y % m month % d % H % m minute % s second ");
Atime = status. m_atime.format ("Last file access time: % Y % m month % d % H % m minute % s second ");
Cstring STR;
STR = ctime + "\ n" + mtime + "\ n" + atime;
MessageBox (STR );
}
4. Get and set file attributes
DWORD getfileattributes (
Lptstr lpfilename // file or folder path
);
Bool setfileattributes (
Lptstr lpfilename, // file name
DWORD dwfileattributes // attributes to be set
);
The obtained file attributes include: file_attribute_archive, file_attribute_hidden,
File_attribute_normal, file_attribute_offline, file_attribute_readonly,
File_attribute_system, file_attribute_temporary
File attributes that cannot be set include:
File_attribute_compressed, file_attribute_directory,
File_attribute_encrypted, file_attribute_reparse_point,
File_attribute_sparse_file, file_attribute_system.
Cfilestatus also defines a set of attributes:
Enum attribute {
Normal,
Readonly,
Hidden,
System,
Volume,
Directory,
Archive
};
You can use if (status. m_attribute & readonly) = file_attribute_readonly) to determine the details of the file. Here, you can use another API to obtain the details of the file:
Handle findfirstfile (
Lptstr lpfilename, // file or folder path R
Lpwin32_find_data lpfindfiledata
);
Bool findnextfile (
Handle hfindfile,
Lpwin32_find_data lpfindfiledata
);
Bool findclose (handle hfindfile );
A win32_find_data structure is obtained;
Typedef struct _ win32_find_data {
DWORD dwfileattributes; // file attributes
Filetime ftcreationtime; // File Creation Time
Filetime ftlastaccesstime; // last file access time
Filetime ftlastwritetime; // last modification time of the file
DWORD nfilesizehigh; // The file length is 32 characters long.
DWORD nfilesizelow; // The file length is 32 characters low
DWORD dwreserved0; // reserved by the System
DWORD dwreserved1; // reserved by the System
Tchar cfilename [max_path]; // long file name
Tchar calternatefilename [14]; // file name in the 8.3 format
} Win32_find_data, * pwin32_find_data;
You can also use another function to obtain the file information:
Bool getfileinformationbyhandle (
Handle hfile, // file handle
Lpby_handle_file_information lpfileinformation
);
The function is filled with the by_handle_file_information struct:
Typedef struct _ by_handle_file_information {
DWORD dwfileattributes;
Filetime ftcreationtime;
Filetime ftlastaccesstime;
Filetime ftlastwritetime;
DWORD dwvolumeserialnumber; // serial number of the disk where the file is located
DWORD nfilesizehigh;
DWORD nfilesizelow;
DWORD nnumberoflinks; // number of links
DWORD nfileindexhigh;
DWORD nfileindexlow;
} By_handle_file_information;
The following is an example:
Handle handle;
Win32_find_data find_data;
Handle =: findfirstfile ("D: \ VSS", & find_data );
Findclose (handle );
Find_data.dwfileattributes = find_data.dwfileattributes | file_attribute_readonly;
: Setfileattributes ("D: \ VSS", find_data.dwfileattributes );
In the above introduction, in addition to setting the attributes of a file, you can also obtain other information about the file during the operation, which can be implemented according to specific needs.
5. Get the file name, file type, file length, and file path.
When using cfile to open a file, you can use the member function
Virtual cstring getfilename () const,
Virtual cstring getfiletitle () const,
Virtual cstring getfilepath () const,
Virtual DWORD getlength () const; throw (cfileexception );
To obtain the relevant information. If the path of a file is c: \ windows \ write \ myfile. WRI, each function obtains the following information:
Myfile. WRI, myfile, c: \ windows \ write \ myfile. WRI.
The object size obtained by getlength is measured in bytes.
You can also use:
Virtual void setlength (DWORD dwnewlen); throw (cfileexception );
Virtual void setfilepath (lpctstr lpsznewname );
To set the file length and path.
Create a new text.txt file under the current file, write something in it, and then run the followingProgram:
Cfile file ("text.txt", cfile: modereadwrite );
Ulonglong length;
Cstring strfilepath;
Length = file. getlength ();
Length = Length + 1024*10;
File. setlength (length );
File. setfilepath ("D: \ text.txt ");
Strfilepath = file. getfilepath ();
MessageBox (strfilepath );
File. Close ();
Finally, we found that the file was changed, but text.txt was not found under the D Drive. The reason is that setfilepath can only specify one path for the file, and setfilepath cannot be used as a mobile file.
Cfile does not provide functions for getting file types. With the above foundation, this is easy to implement.
The API function also provides operations to get the file path. Here is a brief introduction. You can refer to the description of msdnn: getfilesize can get the file size,
Getfullpathname
Function to obtain the complete path name of a file. The result is correct only when the file is in the current directory. The getmodulefilename function is used to obtain the complete path name of a file.
Handle.
For files opened with cfiledialog, you can use its member variable m_ofn, or the member function getfilename, getfiletitle, getfilepath, and getfileext to obtain relevant information.
Cfiledialog (
Bool bopenfiledialog, maid = NULL, maid =
Null, DWORD dwflags = ofn_hidereadonly | ofn_overwriteprompt, lpctstr
Lpszfilter = NULL, cwnd * pparentwnd = NULL );
The parameters are as follows:
• If bopenfiledialog is set to true, the dialog box is displayed. If it is set to false, the dialog box is saved.
• Lpszdefext specifies the default file extension.
• Lpszfilename specifies the default file name.
• Dwflags indicates certain styles.
• Lpszfilter: it specifies the file type available and the corresponding extension. The parameter format is as follows:
"Chart files (*. xlc) | *. xlc | worksheet files (*. xls) | *. xls | data files
(*. Xlc ;*. XLS) | *. xlc ;*. XLS | all files (*. *) | *. * | "; file type description and extension |
Separated. the extensions of files of the same type can be separated. | is used to separate files of the same type, and | is used at the end.
Pparentwnd is the parent window pointer
Cstring filefilter = "all files (*. *) | *. * | ";
Cfiledialog filedialog (true, null, null, ofn_hidereadonly, filefilter, null );
Filedialog. domodal ();
MessageBox (filedialog. getfilename ());
6. Summary
In practice, there are many other methods for operating files. The above is just a few simple methods. I hope you can find the best solution to the problem through the simple introduction above and the specific practices!