Examples of the use of files under VC
Files commonly used are new, read, write files, delete files, read file paths, create folders (directories), copy files, move, rename, read file size,
Find files, traverse files and subdirectories under directories, recursively traverse all files and subdirectories in the directory
Less use of the feature settings file properties, using memory-mapped files, etc.
Here are a few functions for using files:
#include <Windows.h> #include <stdio.h>//create a file handle CreateFile (__in LPCSTR lpfilename, __in DW ORD dwDesiredAccess, __in DWORD dwShareMode, __in_opt lpsecurity_attributes lpsecurityattributes, __in DWORD DwCre Ationdisposition, __in DWORD dwflagsandattributes, __in_opt HANDLE htemplatefile); Parameter//lpfilename//the relative or absolute path of the Action object file//dwdesiredaccess//Indicates the operation access mode of the object file Generic_read, Generic_write, Generic_ Readgeneric_write//dwsharemode//Indicates whether the file is shared with other processes, can read, write, delete shares, etc. file_share_write, if the process exclusively changes the file, set to 0// lpSecurityAttributes//Represents the security attribute of the file handle, which is generally set to NULL, with special requirements special settings//dwcreationdisposition//File operation mode Create_always, Create_new, Open_always, open_existing, truncate_existing//dwflagsandattributes//file attributes and flags, generally set to file_attribute_normal// hTemplateFile//When access rights include Generic_write, you can set a handle to a template file. Generally set to Nullhandle hfile = CreateFile (". \\setting.txt", Generic_ WRITE, 0, NULL, open_always, file_attribute_normal, NULL);//Read data from file bool ReadFile (__in HANDLE hfile, __out_ BcoUnt_part_opt (nNumberOfBytesToRead, *lpnumberofbytesread) __out_data_source (FILE) lpvoid LpBuffer, __in DWORD nNum Berofbytestoread, __out_opt lpdword lpnumberofbytesread, __inout_opt lpoverlapped lpoverlapped); Parameter//hfile file handle, the file operation method should be Generic_read//lpbuffer read the file data store data memory buffer//nnumberofbytestoread indicate need to need to read from the file the size of the data, cannot be larger than the size of the lpbuffer, otherwise it overflows the//lpnumberofbytesread output parameter, which points to the data size of the actual solitude DWORD variable//lpoverlapped: output parameter, if the credit CreateFile function sets the file _flag_overlapped flag, you need to use this parameter, otherwise you can write data to null//from the file bool WriteFile (__in HANDLE hfile, __in_bcount_opt (Nnumbe Rofbytestowrite) lpcvoid lpbuffer,__in DWORD nnumberofbytestowrite, __out_opt lpdword Lpnumberofbyteswritten, __inout_ opt lpoverlapped lpoverlapped); The parameter//hfile file handle//lpbuffer the buffer that needs to be written to the file//nnumberofbytestowrite indicates the size of the data that needs to be written to the file//lpnumberofbyteswritten A variable that points to the size of the data that is actually written//lpoverlapped: output parameter, if the CreateFile function has the FILE_FLAG_OVERLAPPED flag set, you need to use this parameter, otherwise you can get the size of the file for null//DWORD GetFileSize (HANDLE hfile, Lpdword lpFileSizeHigh);//Parameter//handle HFThe Ile file handle//lpdword the lpFileSizeHigh output function, which represents the resulting file size of a high 32-bit, which can be set to null//and a function to get the file size BOOL GetFileSizeEx (HANDLE hfile, Plarge_integer lpfilesize);//delete file bool DeleteFile (LPCTSTR lpfilename);//Parameter LPCTSTR lpFileName indicates the relative path or absolute path of the file to be deleted// The return value bool indicates whether the file was deleted successfully, if the program returned failed, you can get the error message with GetLastError ()//Copy file bool CopyFile (LPCTSTR lpexistingfilename, LPCTSTR Lpnewfilename, BOOL bfailifexists);//Parameter//lpexistingfilename: The original path of the required copy file that already exists//lpnewfilename: The new file path, the destination path of the copied file// Bfailifexists: Indicates whether to overwrite if there is a file in the destination path, if set to true, does not overwrite if present, returns failure (0x50)//Move file (function: Move, rename and catalog) BOOL MoveFile (LPCTSTR Lpexistingfilename, LPCTSTR lpnewfilename);//Parameter//lpexistingfilename: The original path of the required moved file that already exists//lpnewfilename: New file path, The destination path for moving files//copyfileex, MoveFileEx, movefilewithprocessss functions richer//Create a directory or folder bool CreateDirectory (LPCTSTR Lppathname, Lpsecurity_attributes lpsecurityattributes);//lppathname: The directory or path you need to create//lpsecurityattributes: input parameters, Set to null//return value if it fails, you can use the GetLastError function to get the error message,//possible values include error_already_exists (the file already exists), error_path_not_found//Fetch the current directory of the process DWORD GetCurrentDirectory (DWORD nbufferlength, LPTSTR lpbuffer);//Parameter//nbufferlength: input parameter, store the size of the path string buffer, General call Max_path//lpbuffer: output parameter, only want to get the path string//return value: If 0, indicates failure. If not 0, represents the length of the obtained string//sets the current directory of the process bool SetCurrentDirectory (LPCTSTR lppathname);//Parameter//lppathname: input parameter, the path to be set// Get module file name DWORD GetModuleFileName (__in_opt hmodule hmodule, __out_ecount_part (nSize, return + 1) LPSTR lpFileName, __in DWORD nSize);//hmodule: module handle required for module path, set to NULL to indicate current module path//lpfilename: Full path of module//nsize: point to buffer size//return value: if 0 , which indicates a failure. If not 0, indicates the length of the obtained string//To find the file, traverse the files and subdirectories in the specified directory//window API, there is a set of specialized functions and data structures for traversing directories,//They are FindFirstFile, FindNextFile, Win32_find_databool FindNextFile (__in HANDLE hfindfile, __out lpwin32_find_dataa lpfindfiledata),//hFindFile find the directory, you need to make Use wildcards to specify the file target to locate//lpfindfiledata pointer to the WIN32_FIND_DATA structure, handle findfirstfile for the found file and several property information (__in LPCSTR lpFileName, __out lpwin32_find_dataa lpfindfiledata);//lpfilename find handle//lpfindfiledata pointer to win32_find_data structure, to find the file and some properties of the letter//Key structure typedef struct _WIN32_FIND_DATAA {DWORD dwfileattributes; FILETIME Ftcreationtime; FILETIME Ftlastaccesstime; FILETIME ftlastwritetime;dword Nfilesizehigh;dword Nfilesizelow;dword Dwreserved0;dword dwReserved1; CHAR cfilename[MAX_PATH]; CHAR calternatefilename[]; #ifdef _macdword Dwfiletype;dword Dwcreatortype; WORD wfinderflags; #endif} win32_find_dataa, *pwin32_find_dataa, *lpwin32_find_dataa;//implements the traversal of files and subdirectories in the specified directory, and will traverse the resulting files and other properties to print to the interface DWORD Enumeratefileindirectory (LPSTR szpath) {win32_find_data findfiledata; HANDLE Hlistfile; CHAR szfilepath[max_path];//constructs a string representing subdirectories and folder paths, using the wildcard character "*" lstrcpy (Szfilepath, szpath);//The Code of the comment can be used to find all files ending with ". txt"// Lstrcat (Szfilepath, "\\*.txt"); Lstrcat (Szfilepath, "\\*");//Find the first file/directory, get a Find handle hlistfile = FindFirstFile (Szfilepath, &findfiledata); if (hlistfile = = Invalid_handle_value) {return 1;} Else{do {/* If you do not want to display the "." Representing the current level and the previous directory. and ".." You can use the code in the comments section to filter if (lstrcmp (findfiledata.cfilename, Text (".")) = = 0 | | lstrcmp (findfiledata.cfilename, Text ("..")) = = 0) { Continue;} *///print file name, directory name printf ("%s\t\t", findfiledata.cfilename);//Determine whether the file attribute is an encrypted file or folder if (Findfiledata.dwfileattributes & file_attribute_encrypted) {printf ("Encrypt \ n");} Determines whether the file property is a hidden file or folder if (Findfiledata.dwfileattributes & File_attribute_hidden) {printf ("Hide \ n");} Determines whether the file property is a directory if (Findfiledata.dwfileattributes & file_attribute_directory) {printf ("DIR"), or if it is a directory, you can continue searching for Char Sznewfilepath[max_path] = {9};wsprintf (Sznewfilepath, "%s\\%s", szpath, Findfiledata.cfilename); Enumeratefileindirectory (Sznewfilepath);}} while (FindNextFile (Hlistfile, &findfiledata));} return 0;} /*************************************************************savedatatofile function: Read file content parameter: LPSTR szFilePath file Path * * * /dword readfilecontent (LPSTR szfilepath) {//file handle handle Hfileread = null;//Keep file size large_integer lifilesize;//successfully read file data size DWORD dwreadedsize;//Cumulative calculation has read data size Longlong Litotalread = 0;//file data cache byte Lpfiledatabuffer[32] = {0};//Open existing file, read content Hfileread = CreatefiLe (Szfilepath, generic_read, file_share_read, NULL, open_existing, file_attribute_normal, NULL);//Whether the open file succeeds if ( Hfileread = = Invalid_handle_value) {printf ("Open file failed:%d\n", GetLastError ()); return 0;} if (! GetFileSizeEx (Hfileread, &lifilesize)) {printf ("Get File size failed:%d\n", GetLastError ()); return 0;} else{printf ("File Size:%d\n", Lifilesize.quadpart);} Loops through the file and prints the contents of the file while (1) {DWORD i;if (! ReadFile (Hfileread, Lpfiledatabuffer, &dwreadedsize, NULL)) {printf ("Read file error:%d\n", GetLastError ());} printf ("read%d bytes, file content is:", dwreadedsize); for (i = 0; i < dwreadedsize; i++) {printf ("0x%x", Lpfiledatabuffer[i]);} printf ("\ n"); Litotalread + = dwreadedsize;if (Litotalread = = Lifilesize.quadpart) {printf ("End of File read!\n"); break;}} CloseHandle (Hfileread); return 1;} /*************************************************************savedatatofile function: Store data to end of file parameter: LPSTR szFilePath file path Diameter LPVOID lpdata data to be stored DWORD dwdatasize data size (bytes) ******************************************************* ***/dword Savadatatofile (LPSTR szfilepath, LPVoid lpdata, DWORD dwdatasize) {//file handle handle hfilewrite = null;// Successfully written data size DWORD dwwritedatasize = 0;//Open a file that already exists, read the contents hfilewrite = CreateFile (Szfilepath, generic_write, 0, NULL, Create_ Always, File_attribute_normal, NULL), if (Hfilewrite = = Invalid_handle_value) {printf ("Open file failed:%d\n", GetLastError ()); return 0;} Set the file pointer to the end of the file SetFilePointer (hfilewrite, 0, 0, file_end);//write data to file if (! WriteFile (Hfilewrite, lpdata, dwDataSize, &dwwritedatasize, NULL)) {printf ("Write file failed:%d\n", GetLastError ()); return 0;} else{printf ("Write file succeeded, write%d bytes!") \ n ", dwwritedatasize);} CloseHandle (Hfilewrite); return 1;} INI file test code void Testinifile () {///Create a User_setting.ini file under the current program directory handle hfile = Null;hfile = CreateFile (". \\user_ Setting.ini ", generic_write, 0, NULL, open_always, file_attribute_normal, NULL); if (null = = hfile) {printf (" File creation failed! \ n "); return;} CloseHandle (hfile);//Create a section in the User_setting.ini file and write the data bool BRet = False;bret = WritePrivateProfileString (" Column_section "," COlumn_width "," ",". \\user_setting.ini ") BRet = WritePrivateProfileString (" Column_section "," Column_height "," 500 ",". \\user_setting.ini "); BRet = WritePrivateProfileString (" Column_section "," Column_angle "," 0.0 ",". \\user_ Setting.ini "); BRet = WritePrivateProfileString (" Column_attribute "," column_id "," 1 ",". \\user_setting.ini "); BRet = WritePrivateProfileString ("Column_attribute", "Column_color", "Red", ". \\user_setting.ini"); BRet = WritePrivateProfileString ("Column_attribute", "Column_point", "Original", ". \\user_setting.ini");//From User_ A string in the Setting.ini file that reads a key of a section char column_width[100] = {0};D word dwres = 0;dwres = GetPrivateProfileString (" Column_section "," Column_width "," "", "Column_width," ". \\user_setting.ini"); CHAR column_height[100] = {0};d wres = GetPrivateProfileString ("Column_section", "Column_width", "$", Column_height, ". \\user_setting.ini"); CHAR column_angle[100] = {0};d wres = GetPrivateProfileString ("Column_section", "Column_width", "$", Column_angle, ". \\user_setting.ini");//Read the contents of the entire section from the INI file char column_attribute[300] = {0};d wres = Getprivateprofilesection ("Column_attribute", Column_attribute, ". \\user_setting.ini");p rintf ("%s\n", column_attribute);// Read the name of the section from the INI file, if there are two sections in the INI: [SEC1] and [SEC2], then the return is ' Sec1 ', 0, ' sec2 ', 0,0char section_name[100] = {0};d wres = Ge Tprivateprofilesectionnames (Section_name, ". \\user_setting.ini");p rintf ("%s\n", section_name);// Adding the contents of an entire section to another specified section, the contents of the Column_attribute overwrite the contents of the original column_section bret = Writeprivateprofilesection (" Column_section ", Column_attribute,". \\user_setting.ini ");} Get the current directory, get the directory where the program is located, get the module path void Testondirectory () {///for storing the current path char Szcurrentdirectory[max_path] = {0};//used to store the module path Char Szmoudlepath[max_path] = {0};//kernel32 file name and handle LPSTR szKernel32 = "kernel32.dll"; Hmodule hkernel32;//The length of the current path, also used to determine whether to get the success of the DWORD dwcurdirpathlen;//gets the current directory of the process Dwcurdirpathlen = GetCurrentDirectory (max_ PATH, szcurrentdirectory); if (Dwcurdirpathlen = = 0) {return;} printf ("%s\n", Szcurrentdirectory);//sets the current directory of the process to "C: \" lstrcpy (szcurrentdirectory, "c:\\"); SetCurrentDirectory (szcurrentdirectory)) {return;} Under current directory Create subdirectory "Current_dir" CreateDirectory ("Current_dir", NULL);//Get system current Directory Dwcurdirpathlen = GetCurrentDirectory ( MAX_PATH, szcurrentdirectory); if (Dwcurdirpathlen = = 0) {return;} printf ("GetCurrentDirectory Gets the current directory is%s\n", szcurrentdirectory);//Use the null parameter to get the path to this module if (! GetModuleFileName (NULL, Szmoudlepath, MAX_PATH)) {return;} printf ("This module path%s", szmoudlepath);//Gets Kernel32.dll's module handle hKernel32 = LoadLibrary (SZKERNEL32);//gets Kernel32.dll's module handle if ( ! GetModuleFileName (HKernel32, Szmoudlepath, MAX_PATH)) {return;} printf ("Kernel32.dll module path%s", Szmoudlepath); return;} Some functions for displaying properties of a file DWORD Showfiletime (Pfiletime lptime);D Word showfilesize (DWORD Dwfilesizehigh, DWORD Dwfilesizelow) ;D word showfileattrinfo (DWORD dwattribute);D word showfileattribute (LPSTR szpath) {win32_file_attribute_data wfad; printf ("File:%s\n", szpath);//Get file attributes if (! GetFileAttributesEx (szpath, Getfileexinfostandard, &WFAD) {return 1;} Display related information printf ("Creation time: \ t"); Showfiletime (& (Wfad.ftcreationtime));p rintf ("Last access time: \ t"); Showfiletime (& (Wfad.ftlastaccesstime));p rintf ("last modified: \ t"); Showfiletime (& (Wfad.ftlastwritetime));//Display file size showfilesize (Wfad.nfilesizehigh, wfad.nfilesizelow);// Show file Properties Showfileattrinfo (wfad.dwfileattributes); return 0;} DWORD showfiletime (Pfiletime lptime) {//File time structure FILETIME ftlocal;//system time Structure SYSTEMTIME st;// Adjust to time filetimetolocalfiletime (Lptime, &ftlocal) for the system's time zone;//Convert file Time format filetimetosystemtime (&ftlocal, &st) ;//Display time character printf ("%4d year%2d month%2d day,% #02d:% #02d:% #02d \ n", St.wyear, St.wmonth, St.wday, St.wminute, St.wsecond) ; return 0;} DWORD Showfilesize (DWORD Dwfilesizehigh, DWORD Dwfilesizelow) {Ulonglong lifilesize;lifilesize = dwfilesizehigh;// Move to 32-bit lifilesize <<= sizeof (DWORD) * 8;lifilesize + = dwfilesizelow;printf ("File size: \t%i64u bytes \ n", lifilesize); return 0;} DWORD Showfileattrinfo (DWORD Dwattribute) {//Once determines the properties of a file and displays printf ("File attributes: \ t"); if (Dwattribute & FILe_attribute_archive) {printf ("archive\n");} if (Dwattribute & file_attribute_compressed) printf ("Compressed file"); if (Dwattribute & file_attribute_directory) printf ("catalog file"); if (Dwattribute & file_attribute_encrypted) printf ("Encrypted file"); if (Dwattribute & File_attribute_hidden) printf ("Hidden file"); if (Dwattribute & file_attribute_normal) printf ("NORMAL"); if (Dwattribute & File_attribute_ OFFLINE) printf ("OFFLINE"); if (Dwattribute & file_attribute_readonly) printf ("read-only file"); if (Dwattribute & File_ Attribute_sparse_file) printf ("SPARSE"), if (Dwattribute & File_attribute_system) printf ("System files"); if (Dwattribute & file_attribute_temporary) printf ("Temp file");p rintf ("\ n"); return 0;} Add additional properties to the file DWORD Setfilehiddenandreadonly (LPSTR szFileName) {//Get the original attribute DWORD dwFileAttributes = GetFileAttributes ( szFileName);//Add dwfileattributes |= file_attribute_readonly;dwfileattributes |= file_attribute_hidden;//set file properties, and determine if successful if (SetFileAttributes (szFileName, dwfileattributes)) {printf ("file%s is hidden and property set successfully \ n", SzfilENAME);} else{printf ("File Settings failed%d\n", GetLastError ());} return 0;} Copy the file, delete, move int main (int argc, PCHAR argv[]) {if (0 = = lstrcmp ("-D", argv[1]) && argc = = 3) {if (! DeleteFile (Argv[2]) {printf ("Delete file error!\n"); return 1;} else{printf ("Delete file successfully!\n");}} else if (0 = = lstrcmp ("-C", argv[1]) && argc = = 4)//Copy file {if (! CopyFile (Argv[2], argv[3], TRUE)) {//lasterror = = 0X50, file exists if (GetLastError () = = 0X50) {printf ("The file already exists, is it overwritten?"). y/n ", argv[3]); if (' y ' = = GetChar ()) {//copy, overwrite the already existing file if (! CopyFile (Argv[2], argv[3], FALSE)) {printf ("Copy File Error!\n");} else{printf ("Copy succeeded!\n");}} Elsereturn 0;}}} else if (0 = = lstrcmp ("-M", argv[1]) && argc = = 4) {if (! MoveFile (Argv[2], argv[3]) {printf ("Move file error \ n");} else{printf ("parameter error!\n");}} return 0;}
The use of files under VC