69,371
社区成员
发帖
与我相关
我的任务
分享
// Windows
#include <windows.h>
int main(int argc, const TCHAR *argv[])
{
PCTSTR pszFile = argv[1];
HANDLE hFile1 = CreateFile(pszFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile1 != INVALID_HANDLE_VALUE)
{
BYTE Buffer[1024] = { 0 };
DWORD dwReadBytes = 0;
ReadFile(hFile1, Buffer, sizeof(Buffer), &dwReadBytes, NULL);
CloseHandle(hFile1);
}
HANDLE hFile2 = CreateFile(pszFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile2 != INVALID_HANDLE_VALUE)
{
BYTE Buffer[1024] = { 0 };
DWORD dwWrittenBytes = 0;
WriteFile(hFile2, Buffer, sizeof(Buffer), &dwWrittenBytes, NULL);
CloseHandle(hFile2);
}
return 0;
}
// Linux
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>
int main(int argc, const char *argv[])
{
const char *file = argv[1];
int fd1 = open(file, O_RDONLY);
if (fd1 != -1)
{
char buf[1024] = { 0 };
read(fd1, buf, sizeof(buf));
close(fd1);
}
int fd2 = open(file, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd2 != -1)
{
char buf[1024] = { 0 };
write(fd2, buf, sizeof(buf));
close(fd2);
}
return 0;
}