Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

c - Why does open make my file descriptor 0?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...