面试题答案
一键面试可以通过#ifdef
等条件编译指令来实现。
- 关键代码片段如下:
#include <stdio.h>
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#else
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#endif
int main() {
#ifdef _WIN32
int fd = _open("test.txt", _O_RDONLY);
if (fd != -1) {
char buffer[1024];
int bytesRead = _read(fd, buffer, sizeof(buffer));
_close(fd);
buffer[bytesRead] = '\0';
printf("Read from Windows: %s\n", buffer);
}
#else
int fd = open("test.txt", O_RDONLY);
if (fd != -1) {
char buffer[1024];
ssize_t bytesRead = read(fd, buffer, sizeof(buffer));
close(fd);
buffer[bytesRead] = '\0';
printf("Read from Linux: %s\n", buffer);
}
#endif
return 0;
}
- 解释:
#ifdef _WIN32
:这是一个条件编译指令,_WIN32
是Windows平台预定义的宏。如果当前编译环境是Windows,那么#ifdef _WIN32
和#else
之间的代码会被编译,这里使用Windows特定的文件操作函数_open
和_read
。#else
:如果当前编译环境不是Windows,就会编译#else
和#endif
之间的代码,这里使用POSIX标准的文件操作函数open
和read
,适用于Linux等类Unix系统。#endif
:表示条件编译块的结束。