Interpretation of file operation APIs and cfile classes in VC ++ Program Development

Source: Internet
Author: User
Tags filetime readfile

In VC programming, there are two methods to operate files: Using API functions and cfile classes of 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 the archive attribute
· 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 a file or directory.
· 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 postpone write operations on files.
· 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 the File Buffer 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, allow, deny, deny, and deny.

If a handle is returned to open the file. If the file exists before the function is called, the file operation attribute is create_always or open_always. The getlasterror function returns error_already_exists (including the function operation succeeded ), if the previous function does not exist, 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: moderead: open the file for reading only.

· Cfile: modereadwrite open the file for reading and writing.

· Cfile: modewrite: open the file for writing only.

· Cfile: modenoinherit prevents 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: volume exclusive: open the file in exclusive mode, 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 (only used for derived classes ).

· Cfile: typebinary sets the binary mode (used only for derived classes ).

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 lpdistancetomovehigh is null, the function operation is successful and the offset of the data in the current file is returned. If lpdistancetomovehigh is not null, the 32-bit offset of the returned data is placed in lpdistancetomovehigh, 0xffffffff is returned if the function call fails.

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 functions filetimetolocalfiletime () and filetimetosystemtime () to convert them to the local time and system time formats, you can also use localfiletimetofiletime and systemtimetofiletime () to convert back and use setfiletime to set the file creation time, last access time, and last write time. Because the file must be opened before use, 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, and 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 );

If the path of a file is C:/Windows/Write/myfile. WRI, then each function obtains: 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 following program:

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, and the getfullpathname function can get the complete path name of the file, the result is correct only when the file is in the current directory. The getmodulefilename function obtains the complete path name of a file. Some of these functions use the 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, lpctstr lpszdefext = NULL, lpctstr lpszfilename = NULL, DWORD dwflags = empty | optional, 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 some specific 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 (*. *) | *. * | "; the file type description and extension are separated by |. files of the same type can be separated by the extension; separated by |, and ended with |.

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!

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.