open()函数在if条件中时的问题

#include <stdio.h>
#include <fcntl.h>
int main ()
{
        int fd1;
        int fd2;
        if (fd1 = open("./test1", O_RDWR) < 0)
        {
                printf("open test1 error");
        }
        printf("fd1:%d\n", fd1);
        if (fd2 = open("./test1",O_RDWR) < 0)
        {
                printf("open test2 error");
        }
        printf("fd2:%d\n", fd2);
        return 0;
}

运行结果:

fd1:0

fd2:0

  问题:在if的条件中执行open()函数获得的文件描述符总是0。会与stdin冲突。

需要将open()函数和对fd的测试分在不同的语句:

fd1 = open ("./test1", O_RDWR);
if (fd1 < 0)
{
        printf("open test1 error");
}

同学解释:可能是因为if语句执行时有单独的环境。

posted @ 2013-03-22 19:26  svking  阅读(237)  评论(0编辑  收藏  举报