MST
星途 面试题库

面试题:利用C预定义宏实现跨平台代码的条件编译

假设你需要编写一段代码,使其能在Windows和Linux平台上都能运行。要求使用C语言的预定义宏,根据不同平台包含不同的头文件(如Windows下包含<windows.h>,Linux下包含<unistd.h>),并实现一个简单的文件操作函数,例如创建文件。请编写完整代码。
37.3万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>

#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#endif

void createFile(const char *filename) {
#ifdef _WIN32
    HANDLE hFile = CreateFileA(filename, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile != INVALID_HANDLE_VALUE) {
        CloseHandle(hFile);
        printf("File created successfully on Windows.\n");
    } else {
        printf("Failed to create file on Windows.\n");
    }
#else
    int fd = open(filename, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
    if (fd != -1) {
        close(fd);
        printf("File created successfully on Linux.\n");
    } else {
        printf("Failed to create file on Linux.\n");
    }
#endif
}

int main() {
    createFile("test.txt");
    return 0;
}