【问题标题】:Why program in C won't work on Windows?为什么 C 语言的程序不能在 Windows 上运行?
【发布时间】:2014-08-27 09:30:51
【问题描述】:

我有一个用 C 语言在 Linux 中编写的程序,它在 Linux 平台上运行良好,但在 Windows 中却无法运行。它使用代码块(mingw32-gcc)在 Windows 中成功编译,但它没有按预期工作,它只是抛出一个错误并杀死程序。我怎样才能使它在Windows上工作,请帮助。这是代码:

#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
    int i, size, k = 2, ftab, sect = 3;

    char buf[512];
    char vbuf;
    int dev, fil_descr, off=0;

    fil_descr = open(argv[2], O_RDONLY);
    assert(fil_descr > 0);
    read(fil_descr, buf, 512);
    close(fil_descr);

    printf("Bootsector file: %s\n" ,argv[2]);

    dev=open(argv[1], O_RDWR);
    assert(dev > 0);
    write(dev, buf, 512);

    ftab = open("filetable", O_CREAT|O_RDWR);
    sprintf(buf, "{");
    write(ftab, buf, 1);

    for(i = 3; i < argc; i++)
    {   
        off = off + (k * 512);
        lseek(dev, off, SEEK_SET);
        fil_descr=open(argv[i], O_RDONLY);
        assert(fil_descr > 0);
        size = 0;       

        while((read(fil_descr, &vbuf, 1))!=0) 
        {
            size++;
            write(dev, &vbuf, 1);

        }

        k = (size > 512)?2:1;

        sprintf(buf, "%s-%d," ,argv[i], sect);
        write(ftab, buf, strlen(buf));
        printf("Input file \'%s\' written at offset %d\n", argv[i], off);
        close(fil_descr);

        sect = sect + k;
    }

    sprintf(buf,"}");
    write(ftab, buf, 1);

    lseek(ftab, 0, SEEK_SET);
    read(ftab, buf, 512);

    lseek(dev, 512, SEEK_SET);
    write(dev, buf, 512);   
    close (dev);
    close(ftab);    
}

【问题讨论】:

  • but it won't work , it just eject error and program close. 但是哪个错误?
  • "它只是弹出错误" 这是什么意思?您收到错误消息吗?为什么这个错误信息的内容是保密的?
  • “一个问题导致程序停止正常工作。Windows 将关闭该程序并在有解决方案时通知您”
  • 您是否使用预期的参数运行您的程序?你有一些断言......
  • 如何运行应用程序?请完整的命令行。

标签: c linux windows


【解决方案1】:

不是一个不能在 Windows 下运行的 C 程序(尽管 C 是使用的编程语言)。

不可行的是尝试使用面向 Win32 的编译器编译使用 POSIX API 函数(例如 openreadwrite)的程序。这包括使用此环境中不存在的几个标头(如果存在,将声明系统上不存在的函数)。

您要么必须使用 Unix 兼容层(微软曾经出售过,但不确定他们是否仍然这样做,Cygwin 也可能工作),或者使用适当的 C,或者使用本机 Win32 API 函数。

也就是说,如果您切换到使用 C 标准库 I/O 函数或本机 Win32 函数,它也可能无法按预期方式工作。输出“Bootsector:”表明您正在尝试一些根本无法在系统驱动器上运行的东西,并且只能在另一个磁盘上使用管理权限。

【讨论】:

    【解决方案2】:

    为了调试这样的问题,您应该添加一些代码行来帮助您这样做。

    我将程序的相应部分更改为

    printf("Bootsector file: %s\n" ,argv[2]);
    fil_descr = open(argv[2], O_RDONLY);
    if (fil_descr < 0) {
        perror("open");
    }
    
    printf("fil_descr: %d\n", fil_descr);
    assert(fil_descr > 0);
    

    并意识到第二个命令行参数必须是要读取的文件的文件名。

    如果我指定正确,它可以正常工作。

    正在写入第一个文件,其余参数也是要读取的文件名。

    【讨论】:

      【解决方案3】:

      这两个标头都是特定于 linux 的,

      #include <sys/types.h>
      #include <unistd.h>
      

      【讨论】:

      • 不,它们不是特定于 linux 的。
      猜你喜欢
      • 2023-03-05
      • 1970-01-01
      • 2016-05-07
      • 2015-04-23
      • 1970-01-01
      • 2017-09-18
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多