将C程序从Linux迁移到Windows

时间:2013-12-25 13:36:18

标签: c linux windows

我想用open()函数在C中打开一个文件,这是我使用的代码:

int lire(){
    char buf[1024];
    int bytesRead;
    int fildes;
    char path[128];
    mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
    int flags = O_RDONLY;
    printf("\n%s-->Donner l'emplacement du fichier :%s ", CYAN_NORMAL, RESETCOLOR);
    scanf("%s", path);
    fildes = ouvrir(path, flags, mode);
    if(fildes == -1){
        return 0;
    }
    while ((bytesRead = read(fildes, buf, sizeof buf)) > 0)
    {
        write(STDOUT_FILENO, buf, bytesRead);
    }
    close(fildes);
    return 1;
}

int ouvrir(char *path, int flags, mode_t mode)
{
        return open(path, flags, mode);
}

我第一次在Linux中编写了这段代码,它正在运行,但是当我在Windows中运行时,我收到了以下错误消息:

error: 'S_IRUSR' undeclared (first use in this function)|
error: 'S_IWUSR' undeclared (first use in this function)|
error: 'S_IRGRP' undeclared (first use in this function)|
error: 'S_IROTH' undeclared (first use in this function)|

这些是我收录的标题:

#include <sys/types.h> //Specified in man 2 open
#include <sys/stat.h>    
#include <stdio.h>
    #include <fcntl.h> // open function
    #include <unistd.h> // close function
    #include "colors.h"
    #include "const.h"
    #include <ctype.h>
    #include <errno.h>
    #include <string.h>

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:11)

使用Windows时,您需要包含sys\stat.h,并且可用的模式标记为_S_IREAD_S_IWRITE,如果需要可以合并。可以找到文档here

请特别注意这条评论:

  

如果为pmode指定了除上述值以外的值(即使它在另一个操作系统中指定了有效的pmode)或者指定了允许的oflag值以外的任何值,该函数将在Debug模式下生成一个断言并调用参数验证中描述的无效参数处理程序。如果允许继续执行,则该函数返回-1并将errno设置为EINVAL。