Windows平台下S_IFREG的等效替代方案是什么?
Windows平台下C语言S_IFREG宏未定义的替代方案
已引入<sys/stat.h>头文件,但使用S_IFREG时触发“use of undeclared identifier S_IFREG”错误,原因是Windows平台不支持POSIX标准的S_IFREG宏,需使用Windows平台对应的等效宏。
现有代码
int function( command_t* p_cmd ) { char path[MAX_ARG_LEN]; strcpy(path, getenv("PATH")); char *token = strtok(path, ":"); while(token != NULL){ char parameter[MAX_ARG_LEN]; strcpy(parameter, token); strcat(parameter, "/"); strcat(parameter, p_cmd->argv[0]); struct stat buffer; int exists; exists = stat(parameter, &buffer); if(exists == 0 && (S_IFREG & buffer.st_mode)){ strcpy(p_cmd->argv[0] , parameter); return 1; } token = strtok(NULL, ":"); } return 0; }
已引入的头文件
#include <ctype.h> #include <errno.h> #include <fcntl.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h>
解决方案
Windows平台的<sys/stat.h>中,用于标识普通文件的宏是_S_IFREG(注意前缀下划线),直接替换原代码中的S_IFREG即可。修改后的判断条件如下:
if(exists == 0 && (_S_IFREG & buffer.st_mode)){
如果需要兼顾跨平台编译(当前场景虽不需要,但可参考),可添加条件编译:
#if defined(_WIN32) || defined(_WIN64) #define S_IFREG _S_IFREG #endif // 原判断代码不变 if(exists == 0 && (S_IFREG & buffer.st_mode)){
由于你无法添加额外库或修改参数,直接替换宏名称是最直接的解决方式。
内容的提问来源于stack exchange,提问作者greg
相关产品推荐
相关产品推荐

