c++ - Windows (Visual C) 是否有 unistd.h 的替代品?

标签 c++ c windows portability unistd.h

我正在将一个为 Unix 编写的相对简单的控制台程序移植到 Windows 平台 ( Visual C++ 8.0 )。所有源文件都包含“unistd.h”,但该文件不存在。删除它后,我收到关于缺少“srandom”、“random”和“getopt”原型(prototype)的提示。 我知道我可以替换随机函数,并且我很确定我可以找到/修改 getopt 实现。

但我确信其他人也遇到过同样的挑战。 我的问题是:Windows 上有“unistd.h”端口吗?至少有一个包含那些具有 native Windows 实现的函数 - 我不需要管道或 fork 。

编辑:

我知道我可以创建我自己的“unistd.h”,其中包含我需要的东西的替代品 - 特别是在这种情况下,因为它是一个有限的集合。但由于这似乎是一个常见问题,我想知道是否有人已经完成了更大的功能子集的工作。

工作中无法切换到不同的编译器或环境 - 我只能使用 Visual Studio。

最佳答案

由于我们在互联网上找不到版本,所以我们从这里开始一个。
大多数 Windows 移植可能只需要完整 Unix 文件的子集。
这是一个起点。请根据需要添加定义。

#ifndef _UNISTD_H
#define _UNISTD_H    1

/* This is intended as a drop-in replacement for unistd.h on Windows.
 * Please add functionality as needed.
 * https://stackoverflow.com/a/826027/1202830
 */

#include <stdlib.h>
#include <io.h>
#include <getopt.h> /* getopt at: https://gist.github.com/ashelly/7776712 */
#include <process.h> /* for getpid() and the exec..() family */
#include <direct.h> /* for _getcwd() and _chdir() */

#define srandom srand
#define random rand

/* Values for the second argument to access.
   These may be OR'd together.  */
#define R_OK    4       /* Test for read permission.  */
#define W_OK    2       /* Test for write permission.  */
//#define   X_OK    1       /* execute permission - unsupported in windows*/
#define F_OK    0       /* Test for existence.  */

#define access _access
#define dup2 _dup2
#define execve _execve
#define ftruncate _chsize
#define unlink _unlink
#define fileno _fileno
#define getcwd _getcwd
#define chdir _chdir
#define isatty _isatty
#define lseek _lseek
/* read, write, and close are NOT being #defined here, because while there are file handle specific versions for Windows, they probably don't work for sockets. You need to look at your app and consider whether to call e.g. closesocket(). */

#ifdef _WIN64
#define ssize_t __int64
#else
#define ssize_t long
#endif

#define STDIN_FILENO 0
#define STDOUT_FILENO 1
#define STDERR_FILENO 2
/* should be in some equivalent to <sys/types.h> */
typedef __int8            int8_t;
typedef __int16           int16_t; 
typedef __int32           int32_t;
typedef __int64           int64_t;
typedef unsigned __int8   uint8_t;
typedef unsigned __int16  uint16_t;
typedef unsigned __int32  uint32_t;
typedef unsigned __int64  uint64_t;

#endif /* unistd.h  */

关于c++ - Windows (Visual C) 是否有 unistd.h 的替代品?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46403227/

相关文章:

c# - 如何通过安装驱动程序来检查Windows是否繁忙?

C++:将 __PRETTY_FUNCTION__ 附加到 c 字符串

c - 什么是标准输入以及它如何与 fscanf 一起使用?

C - 在非结构或 union 中请求成员 ‘x’

c - 多个值的 OpenMP argmin 缩减

java - Windows 上可靠的 File.renameTo() 替代方案?

python - 使用 python 编码重音字符时出现问题

c++ - 指向数组第 [-1] 个索引的指针

c++ - 在 Windows CE 6.0 中的进程之间共享 GDI 句柄

c++ - 指向类函数数组的指针