使用开放系统调用打开/ etc / passwd

时间:2013-01-17 01:31:26

标签: c

我想逐字节读取/ etc / passwd文件,并希望在std o / p上显示它。这是我的代码

void main(int argc, char *argv[])
{
  int fd, ch;
  int ret;
  if((fd = open("/etc/passwd",O_RDONLY)) == -1);
      perror("open");
  while((ret = read(fd, &ch, sizeof(ch))) != 0)
      putchar(ch);

}

它正确编译但显示开放:成功,为什么我无法显示内容,我做错了什么?

2 个答案:

答案 0 :(得分:1)

在if的右括号后面不应该有分号。这导致了问题。分号实际上是一个空语句,它将在条件为真时执行。由于fd不等于-1,因此调用perror。

答案 1 :(得分:0)

putchar()的参数是int,其值的范围为unsigned char,因此您不应该从文件中读取整个int试图将其打印为一个角色 - 您应该阅读unsigned char。您只需将ch的类型更改为unsigned char即可实现此目的。

if行末尾的额外分号表示,即使perror()成功,您的open()也会出现。