【问题标题】:Successful Write doesn't write anything on the file [duplicate]成功写入不会在文件上写入任何内容[重复]
【发布时间】:2012-06-19 09:51:03
【问题描述】:

首先抱歉,如果这是一个愚蠢的问题(肯定是),但我对 Unix 中 Syscall 的使用真的很陌生。 我试图使用“write”在文件上写一些东西;它正确地创建了文件,但是上面没有写任何东西,这就是代码:

int main(void) {
   int fd;
   char *string = "Test";
   if(fd=open("home/user/test.txt", O_WRONLY | O_APPEND | O_CREAT)==-1){
    perror("Open failed");

   }
   printf("%d\n", strlen(string));
   printf("Wrote %d byte on the file", write(fd,string,strlen(string)));
   close(fd);
   return 0;
}

我的问题在哪里? 谢谢

【问题讨论】:

  • 写返回什么?你在第二个 printf 中得到了什么?

标签: c linux file unix system-calls


【解决方案1】:

问题似乎出在这一行:

fd=open("home/user/test.txt", O_WRONLY | O_APPEND | O_CREAT)==-1

相等比较运算符== 具有更高的优先级,因此首先计算它。因此,不是将文件描述符编号分配给fd,而是将比较结果分配给fd

解决这个问题很简单,因为您可以将比较前的部分用括号括起来 ()

【讨论】:

  • 哦,你是对的,非常感谢你^^
猜你喜欢
  • 1970-01-01
  • 2021-11-29
  • 2019-04-25
  • 1970-01-01
  • 2020-09-29
  • 2014-03-21
  • 1970-01-01
  • 1970-01-01
  • 2015-08-05
相关资源
最近更新 更多