从Linux迁移C程序到Windows

6
我想使用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
在 Windows 上使用哪个编译器?你没有看到任何致命错误“无法打开包含文件..”吗? - P0W
我使用GNU GCC编译器,没有这样的致命错误。 - Renaud is Not Bill Gates
S_IRUSR等在stat.h中,对吗? - Bandrami
看看我的答案,你的头疼就会消失 :D - yan bellavance
1个回答

12

在Windows中,您需要包括sys\stat.h,可用的模式标志是_S_IREAD_S_IWRITE,如果需要可以组合使用。文档可以在这里找到。

特别要注意这个注释:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接