为什么对标准输出的write()不起作用



为什么write(1, lol, 1);行在main函数中不起作用?它只是空白,并在程序结束时返回值0,但当我调用函数filecopy(0,1)时,它能工作吗?

编辑:我包括"syscall.h"

int main(void)
{
    ///// filecopy(0,1)
    char lol = 'D';
    write(1, lol, 1);
    return 0;
}
void filecopy(int from, int to)
{
  int n;
  int buf[100];
  while((n=read(from, buf, 100)) > 0)
    write(to, buf, n);
}

filecopy()函数中,对write()的调用是正确的。

write(to, buf, n);    //buf is a pointer.

在您的main()代码中,问题出现在行

write(1, lol, 1);      // lol is of type char, it's not an address.

write()的第二个参数应该是void *。更改为

  write(1, &lol, 1);

强烈建议在编译器中启用警告,并查看并修复编译器发出的警告。

Write采用地址而非值(http://linux.die.net/man/2/write)。调用写入的正确方法是

int main(void)
{
    ///// filecopy(0,1)
    char lol = 'D';
    write(1, &lol, 1);
    return 0;
}

最新更新