#include <stdio.h>
// 判断当前平台
#ifdef _WIN32
#include <windows.h>
// Windows 特定文件操作函数声明
HANDLE CreateFile(
LPCWSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
);
#elif defined(__linux__)
#include <fcntl.h>
#include <unistd.h>
// Linux 特定文件操作函数声明
int open(const char *pathname, int flags);
ssize_t read(int fd, void *buf, size_t count);
ssize_t write(int fd, const void *buf, size_t count);
int close(int fd);
#endif
int main() {
#ifdef _WIN32
// Windows 平台文件操作
HANDLE hFile = CreateFile(
L"test.txt",
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL
);
if (hFile != INVALID_HANDLE_VALUE) {
// 进行文件读写等操作
CloseHandle(hFile);
} else {
printf("Windows 平台文件创建失败\n");
}
#elif defined(__linux__)
// Linux 平台文件操作
int fd = open("test.txt", O_CREAT | O_RDWR, 0666);
if (fd != -1) {
char buf[1024];
ssize_t read_bytes = read(fd, buf, sizeof(buf));
if (read_bytes > 0) {
// 处理读取的数据
}
ssize_t write_bytes = write(fd, "Hello, Linux!", 13);
if (write_bytes != -1) {
// 写入成功处理
}
close(fd);
} else {
printf("Linux 平台文件创建失败\n");
}
#else
#error "Unsupported platform"
#endif
return 0;
}
- 判断当前平台:
- 在C语言中,可以通过预定义宏来判断当前平台。
_WIN32
宏在Windows平台下被定义,__linux__
宏在Linux平台下被定义。
- 条件编译实现功能裁剪:
- 使用
#ifdef
、#elif
和#endif
进行条件编译。在#ifdef _WIN32
块中,引入Windows特定的头文件(如windows.h
),并调用Windows特定的文件操作函数(如CreateFile
)。
- 在
#elif defined(__linux__)
块中,引入Linux特定的头文件(如fcntl.h
和unistd.h
),并调用Linux特定的文件操作函数(如open
、read
、write
和close
)。
- 如果既不是Windows也不是Linux平台,使用
#error "Unsupported platform"
输出错误信息,表示当前平台不支持。