Writefile Function C++

Writefile Function C++

Im trying to use the WriteFile function. Ive been working off this example

Here the buffer that is passed to WriteFile is filled from ReadFile. But I dont want to do it that way. I just want to write a string like "Example text testing WriteFile" or something. But im not sure what values the parameters should have. Ive tried looking around on google but couldnt find anything. Anyone know how i do this?

2 Answers

From MSDN:

BOOL WINAPI WriteFile(
  __in         HANDLE hFile,
  __in         LPCVOID lpBuffer,
  __in         DWORD nNumberOfBytesToWrite,
  __out_opt    LPDWORD lpNumberOfBytesWritten,
  __inout_opt  LPOVERLAPPED lpOverlapped
);
  • The first argument is the handle to the file.
  • The second argument is a pointer to the data you want to write. In your case it's the string.
  • The third argument is the length of the data you want to write. In your case it will be something like strlen(str).
  • The fourth argument is a pointer to a DWORD variable that will receive the number of bytes actually written.
  • The fifth and last parameter can be NULL for now.

You use it like this:

char str[] = "Example text testing WriteFile";
DWORD bytesWritten;

WriteFile(fileHandle, str, strlen(str), &bytesWritten, NULL);

If WriteFile returns FALSE then there was an error. Use the GetLastError function to find out the error code.

0

A simple example of writing a string:

(hOutFile here is an open file handle from a call to CreateFile):

{
    DWORD dwBytesWritten = 0;
    char Str[] = "Example text testing WriteFile";
    WriteFile( hOutFile, Str, strlen(Str), &dwBytesWritten, NULL );
}

EDIT: Check the MSDN function definition for what each parameter does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova
Author

Elena Rostova

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.