CreateFile, WriteFile, ReadFile

Source: Internet
Author: User
Tags bmp image readfile

Read and write files each software development shows up against must involve the work. The CreateFile function is used to create the corresponding file handle, and the WriteFile function is used to write data to a file, and the ReadFile function reads the data from the file.

CreateFile
This function is used to build the corresponding handle (HANDLE) of the device (file).

//CreateFile函数声明HANDLE CreateFile(LPCTSTP lpFileName,              //文件名DWORD   dwDesiredAccess,         //访问方式DWORD   dwShareMode,             //共享模式LPSECURITY_ATTRIBUTES  lpSecurityAttributes,   //一个指向安全结构的指针,一般设置为NULL即可DWORD   dwCreationDisposition,    //创建方式  DWORD   dwFlagAndAttributes,      //属性HANDLE  hTemplateFile             //复制文件句柄)

The following is a description of the specific parameters

dwdesiredaccess access Mode
Generic_read to allow read access to the device (file)
Generic_write indicates that the device (file) is allowed to write
NULL indicates that only one device (file) is allowed to get information about

dwsharemode sharing mode
NULL means no sharing
File_share_read indicates that the device (file) is allowed to share read access
File_share_write indicates that the device (file) is allowed to share write access

lpsecurityattributes Safety Pointers
A pointer to a lpsecurity_attributes structure that defines the security characteristics of the device (file), which is generally null.

dwcreationdisposition How to create
Create_new Create file, error if file exists
Create_always Create a file that overwrites the previous file (common)
Open_existing file must already exist, requested by device
Open_always If the file does not exist, create it
truncate_existing reduce existing files to zero length

Dwflagandattributes Property
File_attribute_archive marking files as archive properties
Flie_attribute_compressed to mark a file as compressed, or as the default way to mark files in a directory
File_attribute_normal Default Properties
Fiel_attribute_hidden Hidden files or directories
fiel_attribute_readonly files as read-only files
Fiel_attribute_system files as read-only files
File_flag_waite_through the operating system must not postpone write operations to the file
file_flag_overlapped allow overlapping of files
file_flag_no_buffering disable caching of files and write to disk-only sector blocks
File_flag_random_access Optimizing files for random access
File_flag_sequential_scan buffering optimization of files for continuous access
File_flag_delete_on_close Delete file after closing handle, apply to temporary file

ReadFile
The ReadFile function reads the file data into a buffer.

//ReadFile 函数声明ReadFile(     HANDLE hFile,                  //句柄     LPVOID lpBuffer,               //缓冲区指针     DWORD nNumberOfBytesToRead,    //读出的字节数     LPDWORD lpNumberOfBytesRead,   //用于保存实际读出的字节数的存储区域,用于判断是否读取成功     LPOVERLAPPED lpOverlapped      //OVERAPPED结构体指针,一般取NULL    );

WriteFile
The WriteFile function writes data to a file that is more flexible, convenient, and

//WriteFile 函数声明WriteFile(     HANDLE hFile,                  //句柄     LPVOID lpBuffer,               //数据缓冲区指针     DWORD nNumberOfBytesToRead,    //写入的字节数     LPDWORD lpNumberOfBytesRead,   //用于保存实际写入的字节数的存储区域,用于判断是否读取成功     LPOVERLAPPED lpOverlapped      //OVERAPPED结构体指针,一般取NULL    );

Let's take a look at an interesting example from these WINAPI interfaces, (This example comes from NetEase Cloud classroom choice Education)

Hide the file in a BMP file

First, a brief introduction to the BMP file format, is the standard image file format in the Windows operating system
We use Uitraedit to open a BMP file to see the following results:

Let's first look at the structure of the BMP file header

typedefstruct tagBITMAPFILEHEADER{    WORD bfType;//位图文件的类型,必须为BM(1-2字节)    DWORD bfSize;//位图文件的大小,以字节为单位(3-6字节,低位在前)    WORD bfReserved1;//位图文件保留字,必须为0(7-8字节)    WORD bfReserved2;//位图文件保留字,必须为0(9-10字节)    DWORD bfOffBits;//位图数据的起始位置,以相对于位图(11-14字节,低位在前)    //文件头的偏移量表示,以字节为单位}BITMAPFILEHEADER;

The most important thing here is to get the offset of the starting position of the bitmap in order to silently write the file without destroying the original file format.

For each bitmap file, the offset address of the first pixel is fixed, and in the last red box, 00000036 corresponds to the first pixel offset byte amount.


We easily position the position of the first pixel by the offset, at this time each data is composed of 6 bytes, anyway, is the latter three changed the impact is not big, it is difficult to see, so you can hide the data (I think the strongest brain those people can see it)

Anyway, here's a look at the code, mainly the file read and write operations.

//HideInBMP.cpp: Defines the entry point of the console application. //#include "stdafx.h" header files for #include <windows.h>//winapi#include <iostream>#include <cstring>using namespace STD;Char* Getfilecontent (Char*filename, DWORD *filesize) {//used to create a handle, and to open a buffer to read the contents of the file intoHANDLE hfile = Createfilea (filename, generic_read | Generic_write, File_share_write | File_share_read, NULL, open_existing, NULL, or NULL);//File handle    //generic_read | Generic_write indicates that the file is allowed to read and write    //File_share_write | File_share_read to allow shared read and write operations on files    //open_existing indicates that the file must already exist    if(Hfile==invalid_handle_value) {cout<<"Can ' t Open"<< filename << Endl;returnNULL;      } DWORD Dwread; DWORD dwsize = GetFileSize (hfile, &dwread);//Read file size*filesize = dwsize;Char* Cbuf =New Char[dwsize];//Open buffer on heap, waiting to read file dataRtlZeroMemory (Cbuf,sizeof(CBUF));//Fill buffer with 0ReadFile (hfile, Cbuf, dwsize, &dwread,0);//Read in data to buffer    if(Dwread! = dwsize)//Determine if read in normal{cout<<"Read"<<filename<<"failed\n"<<endl;returnNULL; } closehandle (hfile);returnCbuf;//Returns a pointer to the buffer}BOOLSaveFile (Char* BUF,intLenChar* filename) {//For writing data to BMP filesHANDLE hfile = Createfilea (filename, generic_read | Generic_write, File_share_write | File_share_read, NULL, open_always, file_attribute_normal, NULL);//Create handle    //Allow read and write operations    //Allow shared read and write operations    //If the file does not exist, create it, when we want to parse out the TXT file from the BMP is not there, (but I feel here with create_always will not be possible)    //Default Properties    if(hfile = = INVALID_HANDLE_VALUE) {cout<<"Can ' t Open"<< filename << Endl;return false; } setfilepointer (hfile,0,0, File_begin);//handle refers to the top of the fileDWORD Dwwritten;//Save how many bytes were written to the fileWriteFile (hfile, buf, Len, &dwwritten,0);//write data to fileCloseHandle (hfile);return   true;}BOOLHide (Char*secretfilename,Char*bmpfilename) {DWORD dwbmpsize, dwsecretsize;Char* Lpbmp = getfilecontent (Bmpfilename, &dwbmpsize);//Store the original file name    Char* Lpsecret = getfilecontent (Secretfilename, &dwsecretsize); DWORD * Lpfirstpoint = (DWORD *) (Lpbmp +Ten);//Read the offset byte of the first pixel    Char* Lpcurrentbmp = lpbmp + *lpfirstpoint +3; Point pointer to the lower-acting three bytesChar* Lpcurrentsecret = Lpsecret;///First pixel point save secret file size* ((dword*) lpcurrentbmp) = Dwsecretsize;//Save write TXT file size, use when parsingLpcurrentbmp + =6;//6 bytes per pixel     for(; lpcurrentbmp< (lpbmp + dwbmpsize) && Lpcurrentsecret < (Lpsecret + dwsecretsize); Lpcurrentbmp + =6)//cannot be greater than the size of BMP        //Loop writes the entire TXT file sequentially to the buffer{if(dwsecretsize>2) {*lpcurrentbmp = *lpcurrentsecret; * (Lpcurrentbmp +1) = * (Lpcurrentsecret +1); * (Lpcurrentbmp +2) = * (Lpcurrentsecret +2); Lpcurrentsecret + =3; Dwsecretsize-=3; }Else if(dwsecretsize==2) {*lpcurrentbmp = *lpcurrentsecret; * (Lpcurrentbmp +1) = * (Lpcurrentsecret +1); Break; }Else if(dwsecretsize==1) {*lpcurrentbmp = *lpcurrentsecret; Break; }Else{ Break; }} SaveFile (Lpbmp, Dwbmpsize, bmpfilename);//Writes a buffer of TXT data to the BMP image    Delete[] lpbmp;Delete[] Lpsecret;return true;}BOOLRecovery (Char*bmpfilename,Char*secretfilename) {//The saved TXT information is read out to the buffer, and the operation is similar to the writeDWORD dwbmpsize;Char* Lpbmp = getfilecontent (Bmpfilename, &dwbmpsize); DWORD * Lpfirstpoint = (DWORD *) (Lpbmp +Ten);cout<<"First point offset:"<< *lpfirstpoint << Endl; DWORD dwsecretsize = * (DWORD *) (Lpbmp + *lpfirstpoint +3);//Read the file size of the stored txt    cout<< dwsecretsize << Endl;cout<<"Secret File size:"<< dwsecretsize << Endl;Char* Secretbuf =New Char[Dwsecretsize];Char* Lpcurrentbmp = lpbmp + *lpfirstpoint +3+6; for(inti =0; lpcurrentbmp< (lpbmp + dwbmpsize) && i<dwsecretsize; Lpcurrentbmp + =6) {Secretbuf[i] = *lpcurrentbmp; Secretbuf[i +1] = * (Lpcurrentbmp +1); Secretbuf[i +2] = * (Lpcurrentbmp +2); i + =3; } SaveFile (Secretbuf, Dwsecretsize, secretfilename);Delete[] secretbuf;Delete[] lpbmp;return true;}intMainintargcChar*argv[]) {if(argc<3)    {cout<<"Usage"<< argv[0] <<"Encrypt secret_file_name bmp_file_name"<<endl;cout<<"Usage"<< argv[0] <<"Decrypt secret_file_name bmp_file_name"<< Endl;return 0; }if(strcmp(argv[1],"Encrypt") ==0) {Hide (argv[2], argv[3]); }Else if(strcmp(argv[1],"Decrypt")==0) {Recovery (argv[3], argv[2]); }Else{cout<< argc << Endl;cout<< argv[1] << Endl;cout<<"Invalid para"<< Endl; }cout<<"done!"<< Endl;return 0;}

The whole program is simple and interesting, but the powerful features of the WINAPI file read and write reflect the incisively and vividly, corresponding WIN32 console program stamp here
http://download.csdn.net/detail/avalon_y/9532526

CreateFile, WriteFile, ReadFile

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.