【问题标题】:Migrating a C program from Linux to Windows将 C 程序从 Linux 迁移到 Windows
【发布时间】:2013-12-25 13:36:18
【问题描述】:

我想用 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>

我该如何解决这个问题?

【问题讨论】:

  • Windows 上的编译器是什么?您没有看到任何致命错误“无法打开包含文件..”吗?
  • 我使用的是 GNU GCC 编译器,并没有出现这样的致命错误
  • stat.h中不是有S_IRUSR等吗?
  • 在下面看到我的回答,你的头痛就会消失:D

标签: c linux windows


【解决方案1】:

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

特别注意这条评论:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-11
    • 2014-09-17
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    相关资源
    最近更新 更多