CreateFile ReadFile WriteFile Read-write file operation

Source: Internet
Author: User
Tags readfile
The following is a description of this function: CreateFile This is a multifunctional function that can open or create the following objects and return accessible handles: console, communication resource, directory (read-only open), disk drive, file, mail slot, pipeline.
Handlewinapicreatefile (_in_lpctstrlpfilename, _in_dworddwdesiredaccess, _in_dworddwsharemode, _In_opt_LPSECURITY_ Attributeslpsecurityattributes, _in_dworddwcreationdisposition, _in_dworddwflagsandattributes, _In_opt_ Handlehtemplatefile);

For more details Click here for the description of the parameter: http://baike.baidu.com/view/1288759.htm

Here's how to read and write files using this function:

1. Read the file data:

HANDLE hopenfile = (HANDLE) CreateFile ("E:/a.txt", Generic_read, File_share_read, NULL, open_existing, NULL, NULL);
DWORD rsize;
int fileSize = 0;
CHAR *pbuffer;
if (Hopenfile = = INVALID_HANDLE_VALUE)
{
Hopenfile = NULL;

}

FileSize = GetFileSize (Hopenfile, NULL);

pbuffer = (CHAR *) malloc (fileSize);
ReadFile (Hopenfile, pbuffer, FileSize, &rsize, NULL);
Free (pbuffer);

CloseHandle (hfile);

2. Write file operation

DWORD dwBytesWritten = 0;

HANDLE hfile = CreateFile (
"E:/my.txt",//the name of the file or device created or opened (here is the TXT file).
generic_write,//file access rights, write
0,//sharing mode, where setting 0 prevents other processes from opening files or devices
Null,//security_attributes structure, security description, here NULL stands for default security level
create_always,//for operations that exist or do not exist, this is always created
file_attribute_normal,//setting the properties of the file with the cache option
NULL);

if (Hopenfile = = INVALID_HANDLE_VALUE)
{
Hopenfile = NULL;

}

char * Text = "Hello world!"
if (WriteFile (Hfile,text,strlen (text) +1,&dwbyteswritten,null) ==false)
{
cout<< "WriteFile ERROR" <<endl;
return 1;
};

CloseHandle (hfile);

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.