MST

星途 面试题库

面试题:C语言条件编译在跨平台功能裁剪中的应用

已知项目需要在Windows和Linux平台上运行,在Windows平台上使用Windows特定的文件操作函数,在Linux平台上使用Linux特定的文件操作函数。请利用C语言条件编译实现根据不同平台进行功能裁剪,写出完整的源文件框架及关键代码,说明如何判断当前平台。
31.5万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#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;
}
  1. 判断当前平台
    • 在C语言中,可以通过预定义宏来判断当前平台。_WIN32宏在Windows平台下被定义,__linux__宏在Linux平台下被定义。
  2. 条件编译实现功能裁剪
    • 使用#ifdef#elif#endif进行条件编译。在#ifdef _WIN32块中,引入Windows特定的头文件(如windows.h),并调用Windows特定的文件操作函数(如CreateFile)。
    • #elif defined(__linux__)块中,引入Linux特定的头文件(如fcntl.hunistd.h),并调用Linux特定的文件操作函数(如openreadwriteclose)。
    • 如果既不是Windows也不是Linux平台,使用#error "Unsupported platform"输出错误信息,表示当前平台不支持。