VC ++ MFC file and folder operations

Source: Internet
Author: User
Tags filetime

File Attributes

1. Determine whether the file exists

Use the cfile class and cfilestatus class to determine

Cfilestatus filestatus;
If (cfile: getstatus (_ T ("D: // softist.txt"), filestatus ))
Afxmessagebox (_ T ("file exists "));
Else
Afxmessagebox (_ T ("file does not exist "));

Use the cfilefind class to determine

Cfilefind FileFind;

Cstring strpathname = _ T ("D: // softist.txt ");

If (FileFind. findfile (strpathname ))

Afxmessagebox (_ T ("file exists "));

Else

Afxmessagebox (_ T ("file does not exist "));

 

 


 

 

Use the findfirstfile API function to determine the file attributes, date, size, and other attributes. Example:

Win32_find_data findfiledata;
Handle hfind;
Hfind = findfirstfile (_ T ("D: // softist.txt"), & findfiledata );
If (hfind = invalid_handle_value)
{
Afxmessagebox (_ T ("file does not exist "));
}
Else
{
Afxmessagebox (_ T ("file exists "));
Findclose (hfind );
}

2. File date operations. The following figure shows the modification time of the file "D: // softist.txt". After trace, change the modification time of the file to 2000-12-03 12:34:56.

Handle hfile;

Filetime;

Filetime localtime;

Systemtime;

 

Hfile = createfile (_ T ("D: // softist.txt"), generic_read | generic_write,

0, null, open_existing, file_attribute_normal, null );

 

If (hfile! = Invalid_handle_value)

{

Getfiletime (hfile, null, null, & filetime); // get the UTC file time

Filetimetolocalfiletime (& filetime, & localtime); // change to local time

Filetimetosystemtime (& localtime, & systemtime); // change to the system time format

 

Trace ("% 04d-% 02d-% 02d % 02d: % 02d: % 02d/R/N ",

Systemtime. wyear, systemtime. wmonth, systemtime. wday,

Systemtime. whour, systemtime. wminute, systemtime. wsecond );

 

// Change the file time to 12:34:56

Systemtime. wyear = 2000; systemtime. wmonth = 12; systemtime. wday = 3;

Systemtime. whour = 12; systemtime. wminute = 34; systemtime. wsecond = 56;

Systemtimetofiletime (& systemtime, & localtime); // convert it to the file time format

Localfiletimetofiletime (& localtime, & filetime); // change to UTC time

Setfiletime (hfile, null, null, & filetime); // sets the UTC file time.

Closehandle (hfile );

}

3. Set file attributes

Bool setfileattributes (lpctstr lpfilename, DWORD dwfileattributes );

Significance of dwfileattributes

File_attribute_archive

File_attribute_hidden: hide a file

File_attribute_normal normal file

File_attribute_readonly read-only file

File_attribute_system System File

Example:

Setfileattributes (_ T ("D: // softist.txt", file_attribute_readonly );

Copy, move, delete, and rename an object

1. file copy API

Bool copyfile (maid, maid );

Bfailifexists is used to determine whether to abort the copy operation if the target file already exists. False is returned. For example, copy "D: // softist1.txt" to "D: // softist2.txt", even if "D: // softist2.txt" already exists.

Bool Bret = copyfile (_ T ("D: // softist1.txt"), _ T ("D: // softist2.txt"), false );

 

 


 

 

2. File mobile API

Bool movefile (maid, maid );

This function can be used to move a file or directory (including sub-Directories), for example,

Movefile (_ T ("D: // softist.txt"), _ T ("D: // softist2.txt "));

The following API carries the option dwflags to move a file or directory (including subdirectories ).

Bool movefileex (maid, maid, DWORD dwflags );

Significance of dwflags:

Movefile_replace_existing: Specifies whether to replace the target file if it exists.

Move the movefile_delay_until_reboot file and run the mobile job the next time you start the system.

3. delete an object

API:

Bool deletefile (lpctstr lpfilename );

MFC:

Static void Pascal cfile: Remove (lpctstr lpszfilename );

4. File renamed MFC:

Tchar * poldname = _ T ("oldname_file.dat ");

Tchar * pnewname = _ T ("renamed_file.dat ");

Try

{

Cfile: Rename (poldname, pnewname );

}

Catch (cfileexception * PEX)

{

Trace (_ T ("file % 20 s not found, cause = % d/N"), poldname,

Pex-> m_cause );

Pex-> Delete ();

}

Traverse file directories

Traverse the file directory to retrieve all the files in a directory and the file names in the subdirectories. This document is the note of the cfilefind class example. The following program starts from a directory and traces all the members in the directory to the debug output screen in layers.

Void travelfolder (cstring strdir, int ndepth)

{

Cfilefind FileFind; // declare the cfilefind Type Variable

Cstring strwildpath = strdir + _ T ("// *. *"); // all files are listed.

If (FileFind. findfile (strwildpath, 0) // start File Retrieval

{

Bool Bret = true;

While (BRET)

{

Bret = FileFind. findnextfile (); // enumerate a file

If (FileFind. isdots () // If yes. or.

Continue;

For (INT I = 0; I <ndepth; I ++) // print layers with spaces

{

Trace (_ T (""));

}

If (! FileFind. isdirectory () // is not a subdirectory. Print the file name.

{

Cstring strtextout = strdir + cstring (_ T ("//") + FileFind. getfilename ();

Trace (_ T ("file = % S/R/N"), strtextout );

}

Else // if it is a subdirectory, recursively call this function

{

Cstring strtextout = strdir + cstring (_ T ("//") + FileFind. getfilename ();

Trace (_ T ("dir = % S/R/N"), strtextout );

Travelfolder (strtextout, ndepth + 1); // recursively call this function to print files in the subdirectory

}

}

FileFind. Close ();

}

}

// Test and print all the files and subdirectories in/temp of drive D to the debug output screen.

Void test ()

{

Travelfolder (cstring (_ T ("D: // Temp"), 0 );

}

File directory operations

1. Create a directory (API)

Bool createdirectory (lpctstr pstrdirname); // The pstrdirname is the full path.

2. delete a directory (API)

Bool removedirectory (lpctstr lppathname );

3. Determine whether a directory exists (shell function)

# Include <shlwapi. h> # pragma comment (Lib, "shlwapi. lib ") if (pathisdirectory (_ T (" D: // Temp ") afxmessagebox (_ T (" ")); else afxmessagebox (_ T ("nonexistent "));

 

 


 

 

4. Obtain the current directory (API)

DWORD getcurrentdirectory (DWORD nbufferlength, lptstr lpbuffer );

5. Obtain the directory of the execution file (API)

DWORD getmodulefilename (hmodule, lptstr lpfilename, DWORD nsize );

6. Obtain the function directory (shell function)

Bool shgetspecialfolderpath (hwnd hwndowner, lptstr lpszpath, int nfolder, bool fcreate );

Example: Read my archive directory

Tchar szdirfile [1024];
Memset (szdirfile, 0, sizeof (szdirfile ));
Bool Bret = shgetspecialfolderpath (null, szdirfile, csidl_personal, true );
If (BRET)
{
Afxmessagebox (szdirfile );
}

7. Select a directory dialog box

You can use shell function to display a dialog box for selecting directories.

 

# Include <shlobj. h>

Int callback _ browsecallbackproc (hwnd, uint umsg, lparam, lparam pdata)

{

Tchar szdir [max_path];

Switch (umsg)

{

Case bffm_initialized:

// Wparam is true since you are passing a path.

// It wocould be false if you were passing a pidl.

Sendmessage (hwnd, bffm_setselection, true, (lparam) pdata );

Break;

Case bffm_selchanged:

// Set the status window to the currently selected path.

If (shgetpathfromidlist (lpitemidlist) lparam, szdir ))

{

Sendmessage (hwnd, bffm_setstatustext, 0, (lparam) szdir );

}

Break;

}

Return 0;

}

 

Cstring getfolderfullpath (lpctstr lpszdefault)

{

Tchar buffdisplayname [max_path];

Tchar fullpath [max_path];

Browseinfo;

Lpitemidlist;

 

Zeromemory (& browseinfo, sizeof (browseinfo ));

Browseinfo. pszdisplayname = buffdisplayname;

Browseinfo. lpsztitle = _ T ("select a directory ");

Browseinfo. ulflags = bif_returnonlyfsdirs;

Browseinfo. lparam = (lparam) lpszdefault;

Browseinfo. lpfn = _ browsecallbackproc;

 

If (! (Lpitemidlist = shbrowseforfolder (& browseinfo )))

{

Afxmessagebox (_ T ("No directory selected "));

Return cstring (_ T (""));

}

Else

{

Shgetpathfromidlist (lpitemidlist, fullpath );

Cotaskmemfree (lpitemidlist );

Return cstring (fullpath );

}

}

 

Void ctest77dlg: onbnclickedbutton1 ()

{

Cstring strfolderfullpath = getfolderfullpath (_ T ("D: // Temp "));

If (strfolderfullpath! = _ T (""))

Afxmessagebox (strfolderfullpath );

}

 

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/susik/archive/2010/08/25/5838841.aspx

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.