2016-03-10 57 views
0

我有一个学校项目。我必须用C编写一个基本的虚拟机,它能够托管一个CoreWar游戏。我应该从二进制文件读取,但我不允许使用fopen,fread或fseek。在没有打开的情况下在C中读取二进制文件

我必须使用read,writelseek

我真的不明白我应该怎么做,我在互联网上发现的一切都说我必须使用fopen“rb”模式。

+6

使用'open'系统调用'O_BINARY'选项(如果你的编译器说这个选项是未定义的,删除它)。你是否读过''读'''写'和'lseek'?提示:它们也是系统调用,因此将其添加到查询中将有助于过滤结果。 – MikeCAT

+0

我做过谷歌阅读写lseek并打开,但我没有遇到任何像你提到的O_BINARY选项。我想我并不擅长使用Google。无论如何,感谢您的快速答案! – Henry

+0

即使在谷歌上也试试'man read'。然后查找“另请参见”部分。 –

回答

3

下面是使用您需要使用的低级函数来读取文件的完整示例。

用您自己的代码替换注释/* Process the data */,该代码对读取的数据执行了一些有用的操作。

int rfd; /* File descriptor. */ 
    char buffer[BUFFER_SIZE]; /* Buffer to put file content into */ 
    int bufferChars; /* number of characters returned by the read function */ 

    /* Open the file */ 
    if ((rfd = open(argv[1], O_RDONLY, 0)) < 0) 
     perror("Open failed."); 

    /* Read and process the file */ 
    while (1) 
    { 
     /* Normal case --- some number of bytes read. */ 
     if ((bufferChars = read(rfd, buffer, BUFFER_SIZE)) > 0) 
     { 
      /* Process the data */ 
     } 
     else if (bufferChars == 0) /* EOF reached. */ 
     break; 
     else /* bufferChars < 0 --- read failure. */ 
     perror("Read failed."); 
    } 

    close(rfd); 
+0

你的回答让我明白我没有得到。我实际上不得不打开一个特定的选项/标志来读取二进制文件。我只需要像其他文件一样阅读它。对上述问题的评论现在更有意义。感谢您的帮助。 – Henry

相关问题