This time we are going to use Windows SDK.
We are going to write a program which would accept file name as command line parameter and would print out content of that file. This could be done just in plane C or C++ code for compatibility, but I want to show you how to use Windows SDK in your applications.
So fire up text editor (e.g. Notepad++) and type:
#include <stdio.h>
#include <windows.h>
#include <iostream>
int main(int argc, char* argv[])
{
if(argc < 2)
{
std::cout << "Usage: PrintFile.exe <file name>" << std::endl;
return 1;
}
HANDLE hFile = ::CreateFile(argv[1], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (INVALID_HANDLE_VALUE == hFile)
{
std::cout << "Failed to open file. Error: " << GetLastError() << std::endl;
}
else
{
const DWORD dwBuf{ 512 };
char buf[dwBuf];
DWORD dwRead{ 0 };
while (::ReadFile(hFile, buf, dwBuf-1, &dwRead, NULL) && 0 != dwRead)
{
buf[dwRead] = 0;
std::cout << buf;
}
std::cout << std::endl;
::CloseHandle(hFile);
}
return 0;
}
save it as PrintFile.cpp and lets compile it.
Now open Visual C++ 2015 x86 Native Build Tools Command Prompt (not regular Command Prompt) and execute this command:
cl.exe /W4 /EHsc PrintFile.cpp /link Kernel32.lib /out:PrintFile.exe
Hopefully there are no error, and you can execute it:
PrintFile.exe PrintFile.cpp
you should see content of your source file on the screen.
Let's analyze our compiler parameters:
/W4 - show all the warnings
/EHsc - enables C++ exception handling model
/link - pass the rest of the line to the linker (link.exe)
/out: - name of the output file (executable)
Kernel32.lib - name of the library to link with.
Why Kernel32.lib you may ask - if you open help for the CreateFile function and scroll to the bottom you would see which library this function is located: Library Kernel32.lib , so that's the library you should include in your linking process.