Skip to content

Instantly share code, notes, and snippets.

@FedericoPonzi
Created October 17, 2014 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FedericoPonzi/c93b4b6be81cff9052d4 to your computer and use it in GitHub Desktop.
Save FedericoPonzi/c93b4b6be81cff9052d4 to your computer and use it in GitHub Desktop.
Create and write inside a file using the Win32api in C.
#include <windows.h>
#include <stdio.h>
int main(int argc, CHAR *argv[])
{
HANDLE hFile;
char DataBuffer[] = "This ia s test string to be written.";
DWORD dwBytesToWrite = (DWORD) strlen(DataBuffer);
DWORD dwBytesWritten = 0;
printf("\n");
if(argc != 2)
{
puts("Errro");
return 1;
}
hFile = CreateFile(argv[1],
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if(hFile == INVALID_HANDLE_VALUE)
{
printf("error: %d", GetLastError());
return 2;
}
printf("Writing %d bytes to %s. \n", dwBytesToWrite, argv[1]);
while( dwBytesWritten < dwBytesToWrite)
{
if (FALSE == WriteFile(hFile,
DataBuffer + dwBytesWritten,
dwBytesToWrite- dwBytesWritten,
&dwBytesWritten,
NULL))
{
printf("could not write, error: %x", GetLastError());
CloseHandle(hFile);
}
}
printf("Wrote %d bytes to %s successfully. \n", dwBytesWritten, argv[1]);
CloseHandle(hFile);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment