Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File Descriptors, open() returns zero

Tags:

c

i open a file and want to write something in it. The problem is that the fd2 for some reason is 0. Instead of writting in the file, it writes on terminal. I dont close(0) anywhere in my code. Why do i get fd = 0 and not for example 3. The reason that writes on terminal is that the value of fd is zero? I know that fd = 0 is for standard input,

Any Ideas? Thank you.

if ((fd2 = open(logFile, O_RDWR |O_APPEND | O_CREAT , 0666) == -1))
    DieWithError("open() failed");

printf("FD2 = %d",fd2);     //returns me zero

bzero(tempStr, sizeof(tempStr));
bzero(hostname, sizeof(hostname));

gethostname(hostname, sizeof(hostname));

sprintf(tempStr, "\n%sStarting FTP Server on host %s in port %d\n", ctime(&currentime), hostname, port);

if (write(fd2, tempStr, strlen(tempStr)) == -1)
    DieWithError("write(): failed");
like image 225
Kelis Avatar asked Nov 01 '12 01:11

Kelis


1 Answers

Your conditional is off. Mind the parentheses. It should be:

if ((fd2 = open(logFile, O_RDWR |O_APPEND | O_CREAT , 0666)) == -1)
//                                                        ^^^    ^^^

Sometimes it might be best not to outsmart yourself:

int fd = open(...);

if (fd == -1) { DieWithError(); }
like image 154
Kerrek SB Avatar answered Sep 24 '22 21:09

Kerrek SB