The CreateFile, ReadFile, and WriteFile of file operations

Source: Internet
Author: User
Tags readfile

1. CreateFile

The function is to create or open a file or I/O device, commonly used in the form of I/O file, file stream, directory, physical Disk, volume, terminal flow and so on. If the execution succeeds, the file handle is returned. Invalid_handle_value indicates an error and the GetLastError is set.
The declaration definition of a function:

  HANDLE WINAPI CreateFile(  _In_      LPCTSTR lpFileName,                _In_      DWORD dwDesiredAccess,  _In_      DWORD dwShareMode,  _In_opt_  LPSECURITY_ATTRIBUTES lpSecurityAttributes,  _In_      DWORD dwCreationDisposition,  _In_      DWORD dwFlagsAndAttributes,  _In_opt_  HANDLE hTemplateFile);

Parameter list:

Parameters Type Description
lpFileName String, the name of the file to open
dwDesiredAccess Long, if Generic_read is allowed to read access to the device, if Generic_write is allowed to write access to the device (can be used in combination), or zero to allow only information about one device to be obtained
dwShareMode Long, 0 is not shared, file_share_read and/or file_share_write means shared access to the file is allowed
lpSecurityAttributes Security_attributes, pointer to a security_attributes structure that defines the security characteristics of the file (if supported by the operating system)
dwCreationDisposition Long, one of the following constants: Create_new create file, if file exists error create_always create file, overwrite previous file; open_existing file must already exist. requested by the device; open_always if the file does not exist, create it; truncate_existing reduce existing files to zero length
dwFlagsAndAttributes Long, one or more of the following constants: File_attribute_archive Tag Archive properties, file_attribute_compressed to mark files as compressed, or to mark the default compression of files in the directory; file_ Attribute_normal default properties; File_attribute_hidden hidden files or directories; file_attribute_readonly files are read-only; File_attribute_system files are system files The File_flag_write_through operating system must not postpone writing to the file; file_flag_overlapped allows overlapping of files; file_flag_no_buffering prevents buffering of files. Files can only be written to disk volumes, file_flag_random_access is optimized for random access, and File_flag_sequential_scan is optimized for continuous access to the file buffers; file_flag_delete _on_close the file is deleted after the last open handle has been closed. Particularly suitable for temporary documents;
hTemplateFile Long, if not zero, specifies a file handle. The new file will copy the extended properties from this file
2. ReadFile

Reads data from a file pointer to a file, supports both synchronous and asynchronous operations, and, if the file is opened without indicating file_flag_overlapped, when the program call succeeds, It saves the number of bytes actually read from the file to the address space indicated in Lpnumberofbytesread. File_flag_overlapped allows overlapping operations on files.
function declaration Definition:

  BOOL WINAPI ReadFile(  __in          HANDLE hFile,                   // 文件句柄  __out         LPVOID lpBuffer,                // 接收数据用的 buffer  __in          DWORD nNumberOfBytesToRead,     // 要读取的字节数  __out         LPDWORD lpNumberOfBytesRead,    // 实际读取到的字节数  __in          LPOVERLAPPED lpOverlapped       // OVERLAPPED 结构,一般设定为 NULL );

code example:

BOOLRead (Char*filepath) {HANDLE pFile; DWORD fileSize;Char*buffer,*tmpbuf;    DWORD Dwbytesread,dwbytestoread,tmplen; PFile = CreateFile (Filepath,generic_read, File_share_read,NULL, Open_existing,//Open a file that already existsFile_attribute_normal,NULL);if(PFile = = INVALID_HANDLE_VALUE) {printf ("Open File error!\n"); CloseHandle (PFile);return FALSE; } fileSize = GetFileSize (PFile,NULL);//Get the file sizeBuffer = (Char*) malloc (fileSize);    ZeroMemory (buffer,filesize);    Dwbytestoread = fileSize; dwBytesRead =0; tmpbuf = buffer; Do{//Cycle through the files to ensure that the full file is readReadFile (Pfile,tmpbuf,dwbytestoread,&dwbytesread,NULL);if(dwBytesRead = =0) Break;        Dwbytestoread-= dwBytesRead;        Tmpbuf + = dwBytesRead; } while(Dwbytestoread >0);//TODO processing read Data bufferFree (buffer); CloseHandle (PFile);return TRUE;}
3. WriteFile

Writes data to a file. This function is much more flexible than the fwrite function. This function can also be applied to the processing of communication devices, pipelines, sockets, and postal slots. When returned, TRUE (not 0) indicates success, otherwise zero is returned. The GetLastError is set.
function declaration Definition:

BOOL WINAPI WriteFile(  __in          HANDLE hFile,                   // 文件句柄  __in          LPCVOID lpBuffer,               // 要写入的数据  __in          DWORD nNumberOfBytesToWrite,    // 要写入的字节数  __out         // 实际写入的字节数  __in          LPOVERLAPPED lpOverlapped       // OVERLAPPED 结构,一般设定为 NULL);

code example:

BOOLWrite (Char*buffer, DWORD contentlen) {HANDLE pFile;Char*tmpbuf;    DWORD Dwbyteswrite,dwbytestowrite; PFile = CreateFile (Filepath,generic_write,0,NULL, Create_always,//Always create filesFile_attribute_normal,NULL);if(PFile = = INVALID_HANDLE_VALUE) {printf ("Create file error!\n"); CloseHandle (PFile);return FALSE;    } dwbytestowrite = Contentlen; Dwbyteswrite =0; tmpbuf = buffer; Do{//Loop write file to ensure full file is writtenWriteFile (Pfile,tmpbuf,dwbytestowrite,&dwbyteswrite,NULL);        Dwbytestowrite-= Dwbyteswrite;        Tmpbuf + = Dwbyteswrite; } while(Dwbytestowrite >0); CloseHandle (PFile);return TRUE;}

The CreateFile, ReadFile, and WriteFile of file operations

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.