Win32API ファイルを扱う CreateFile, ReadFile, WriteFile, CloseHandle

Win32APIでファイルを扱う


使用するAPI

  • CreateFile

  • ReadFile

  • WriteFile

  • CloseHandle

  • GetStdHandle

  • CreateFileの引数については、以下のURLを参照
    http://msdn.microsoft.com/ja-jp/library/cc429198.aspx


  • ファイルからデータを読み込み、コンソールにそのデータを出力する

  • #include <windows.h>
    
    int main()
    {
    	HANDLE hFile;
    	char *lpFileName = "test.txt";
    	char szBuff[1024];
    	DWORD dwNumberOfReadBytes;
    	DWORD dwNumberOfBytesWritten;
    	BOOL bRet;
    
    	hFile = CreateFile(lpFileName,
    		GENERIC_READ,
    		FILE_SHARE_READ,
    		NULL,
    		OPEN_EXISTING,
    		FILE_ATTRIBUTE_NORMAL,
    		NULL
    		);
    	if (hFile == INVALID_HANDLE_VALUE) {
    		printf("CreateFile Failed\n");
    		return 1;
    	}
    
    	bRet = ReadFile(hFile,
    			szBuff,
    			sizeof(szBuff)/sizeof(szBuff[0]),
    			&dwNumberOfReadBytes,
    			NULL);
    
    	if (!bRet) {
    		printf("ReadFile Failed\n");
    		CloseHandle(hFile);
    		return 1;
    	}
    
    	WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), 
    		szBuff, 
    		dwNumberOfReadBytes, 
    		&dwNumberOfBytesWritten, 
    		NULL);
    
    	CloseHandle(hFile);
    
    
    	return 0;
    }