我正在使用管道和分支的程序,需要将写入结束更改为输出文件.但是当我打开一个文件时,文件描述符为0,这通常是stdin,但我认为这是我的一些问题的原因.这是我的代码
if (outputfd = open("file", O_RDWR | O_CREAT | O_TRUNC) == -1)
{
// open failed
}
Run Code Online (Sandbox Code Playgroud)
有人能告诉我为什么它是0吗?或者如何解决?
outputfd在你的代码行中不是输出文件描述符,而是等于FALSE(0).这是因为返回的文件描述符open不是== -1
它应该是:
outputfd = open("file", O_RDWR | O_CREAT | O_TRUNC);
if (outputfd < 0)
{
// error handling code
}
Run Code Online (Sandbox Code Playgroud)
或者它应该是:
if ( ( outputfd = open("file", O_RDWR | O_CREAT | O_TRUNC) ) == -1)
{
// error handling code
}
Run Code Online (Sandbox Code Playgroud)
请注意,这需要3个额外的括号 - 一个右括号和两个左括号.
只是说明了doron的答案:
>> outputfd = open("file", O_RDWR | O_CREAT | O_TRUNC) == -1)
让我们简化:首先删除错误并添加额外的标点,使其看起来像一个真正的诡计
outputfd = open("file", O_RDWR | O_CREAT | O_TRUNC) == -1;
Run Code Online (Sandbox Code Playgroud)
现在,用占位符替换函数参数
outputfd = open(<PLACEHOLDER>) == -1;
Run Code Online (Sandbox Code Playgroud)
添加括号
outputfd = (open(<PLACEHOLDER>) == -1);
Run Code Online (Sandbox Code Playgroud)
什么时候打开()-1的结果?当操作失败时.因此,我们假设操作没有失败,并用正数替换open
outputfd = (<POSITIVENUMBER> == -1);
Run Code Online (Sandbox Code Playgroud)
没有正数可以等于-1(禁止转换问题)所以相等性测试总是假的...而且假的C,根据定义,是0
outputfd = 0;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3041 次 |
| 最近记录: |