我正在将一个为Unix编写的相对简单的控制台程序移植到Windows平台(Visual C++ 8.0).所有源文件都包含"unistd.h",但它并不存在.删除它后,我会收到关于将原型误写为"srandom"、"random"和"getopt"的投诉.

但我相信其他人也遇到了同样的挑战. 我的问题是:Windows有没有"unistd.h"的端口?至少有一个包含那些具有本机Windows实现的函数-我不需要管道或派生.

EDIT:

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

在工作中切换到不同的编译器或环境是不可能的——我被Visual Studio困住了.

推荐答案

既然我们在互联网上找不到一个版本,我们就从这里开始吧

#ifndef _UNISTD_H
#define _UNISTD_H    1

/* This is intended as a drop-in replacement for unistd.h on Windows.
 * Please add functionality as neeeded.
 * 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++相关问答推荐

是否可以在C中进行D3 D12申请?

了解一些CLIPS原语数据类型

getchar读css + z还是返回css?

在C中使用动态内存分配找到最小的负数

C/SDL程序,渲染不使用我的渲染器

为什么内核使用扩展到前后相同的宏定义?

struct 上的OpenMP缩减

C语言编译阶段与翻译阶段的关系

致命:ThreadSaniizer:在Linux内核6.6+上运行时意外的内存映射

N的值设置为0或1(未定义的行为),而我正在try 学习realloc和Malloc的用法

不同出处的指针可以相等吗?

为四维数组中的Dim-1和Dim-3重新分配空间

C";中的ANN运行时判断失败#2-变量outputLayer;周围的堆栈已损坏.运行后出错

C++中PUTS函数的返回值

在文件描述符上设置FD_CLOEXEC与将其传递给POSIX_SPOWN_FILE_ACTIONS_ADCLOSE有区别吗?

memcmp 是否保证按顺序比较字节?

在 C/C++ 中原子按位与字节的最佳方法?

为什么 C 字符串并不总是等同于字符数组?

在 C 中的 scanf() 格式说明符中使用宏获取字符串长度

C23 中的 [[reproducible]] 和 [[unsequenced]] 属性是什么?什么时候应该使用它们?