使用C库
#include <stdio.h>
#include <errno.h>
#define BUFFER_SIZE 256
int main(int argc,char* argv[]) {
FILE* infile, * outfile;
char rec[BUFFER_SIZE];
size_t byteIn, byteOut;
if (argc !=3)
{
printf("usage: cp file file2\n");
return 1;
}
fopen_s(&infile,argv[1], "rb");
if (infile == NULL)
{
perror(argv[1]);
return 2;
}
fopen_s(&outfile,argv[2], "wb");
if (outfile == NULL)
{
perror(argv[2]);
return 3;
}
while ((byteIn = fread(rec,1,BUFFER_SIZE,infile))>0)
{
byteOut = fwrite(rec, 1, BUFFER_SIZE, outfile);
if (byteOut != byteIn)
{
perror("fatal write error ");
return 4;
}
}
fclose(infile);
fclose(outfile);
return 0;
}
使用windows 原生api
字符问题
#include <stdio.h>
#include <Windows.h>
#define BUFFER_SIZE 256
int main(int argc,LPTSTR argv[]) {
HANDLE hIn, hOut;
DWORD nIn, nOut;
CHAR buffer[BUFFER_SIZE];
if (argc < 3)
{
printf("usage: cp file file2\n");
return 1;
}
hIn = CreateFile(argv[1], GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if (hIn == INVALID_HANDLE_VALUE)
{
wprintf(argv[2]);
printf("can not open file .error: %x\n", GetLastError());
return 2;
}
hOut = CreateFile(argv[2], GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hOut == INVALID_HANDLE_VALUE)
{
printf("can not open outfile.error: %x\n", GetLastError());
return 3;
}
while (ReadFile(hIn,buffer,BUFFER_SIZE,&nIn,NULL) && nIn > 0)
{
WriteFile(hOut, buffer, BUFFER_SIZE, &nOut, NULL);
if (nIn != nOut)
{
printf("fatal write error:%x\n", GetLastError());
return 4;
}
}
CloseHandle(hIn); CloseHandle(hOut);
return 0;
}
#include <stdio.h>
#include <Windows.h>
#include <strsafe.h>
int main(int argc,LPCWSTR argv[]) {
WCHAR buffer[128];
::StringCchPrintf(buffer,_countof(buffer),L"this is my string from %u",::GetCurrentProcessId);
::MessageBox(nullptr,buffer,L"String Demo",MB_OK|MB_ICONINFORMATION);
WCHAR path[MAX_PATH];
::GetSystemDirectory(path,_countof(path));
printf("system directory : %ws\n", path);
WCHAR computerName[MAX_COMPUTERNAME_LENGTH];
DWORD len = _countof(computerName);
if (!::GetComputerName(computerName, &len))
{
printf("computer name is : %ws (%u)\n", computerName,len);
}
SHELLEXECUTEINFO sei = { sizeof(sei) };
sei.lpFile = L"c:\\windows\\win.ini";
sei.lpVerb = L"open";
sei.nShow = SW_SHOWNORMAL;
::ShellExecuteEx(&sei);
return 0;
}
获取windows 版本
#include <Windows.h>
#define BUILD_WINDOWS
#include <stdio.h>
#include <VersionHelpers.h>
int main()
{
OSVERSIONINFO vi = { sizeof(vi) };
::GetVersionEx(&vi);
printf("%u .%u .%u", vi.dwMajorVersion, vi.dwMinorVersion, vi.dwBuildNumber);
return 0;
}