Why does open make my file descriptor 0?

前端 未结 4 1335
自闭症患者
自闭症患者 2020-12-07 03:52

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 usuall

4条回答
  •  旧巷少年郎
    2020-12-07 04:51

    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.

提交回复
热议问题