问题
I'm working on a program that is using a pipe and forks and need to change the write end to an output file. But when I open a file the file descriptor is 0 which is usually stdin but which I think is the cause of some of my problems. Here is my code
if (outputfd = open("file", O_RDWR | O_CREAT | O_TRUNC) == -1)
{
// open failed
}
Can someone let me know why it is 0? Or how to fix it?
回答1:
It's because you're comparing it to -1
.
outputfd
doesn't get the result of open
. It gets the result of the check for -1
.
回答2:
outputfd
in your line of code is not the output file descriptor but rather is equal to FALSE
(0). This is because the file descriptor returned by open
is not == -1
It should read:
outputfd = open("file", O_RDWR | O_CREAT | O_TRUNC);
if (outputfd < 0)
{
// error handling code
}
Or it should read:
if ( ( outputfd = open("file", O_RDWR | O_CREAT | O_TRUNC) ) == -1)
{
// error handling code
}
Note that this required 3 extra parentheses - one right parenthesis and two left.
回答3:
Just illustrating doron's answer:
>> outputfd = open("file", O_RDWR | O_CREAT | O_TRUNC) == -1)
Let's simplify: first remove errors and add extra punctutation to make it look like an actual stement
outputfd = open("file", O_RDWR | O_CREAT | O_TRUNC) == -1;
Now, replace function parameters with a placeholder
outputfd = open(<PLACEHOLDER>) == -1;
Add parenthesis
outputfd = (open(<PLACEHOLDER>) == -1);
When is the result of open() -1? When the operation failed. So let's assume the operation didn't fail and replace the open with a positive number
outputfd = (<POSITIVENUMBER> == -1);
No positive number can ever be equal to -1 (barring conversion problems) so the equality test is always false ... and false, in C
is, by definition, 0
outputfd = 0;
回答4:
In C, relational operators have higher precedence than assignment operators.
来源:https://stackoverflow.com/questions/3795351/why-does-open-make-my-file-descriptor-0