Insane Insane - 1 month ago 9
C Question

Program hangs after opening file with open and fdopen

I'm using

open()
with
O_RDWR
and then using the descriptor in
fdopen()
with
"r+"
. I check that the file exists first with
access()
, and check for
open()
returning -1 then check that the
FILE *fp
set from
fdopen()
isn't
NULL
.

Now whenever I use any function such as
fgets()
or
fgetc()
with
fp
the program hangs in my terminal. I get no compiler warnings. Any ideas?



#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char **argv) {
char buffer[512];
int file_descriptor;
FILE *file;

if (argc != 2) {
puts("ERROR: Missing argument");
exit(0);
}
else if (access(argv[1], F_OK) == -1) { // Check if file exists
puts("ERROR: File does not exist");
exit(0);
} else if (file_descriptor = open(argv[1], O_RDWR) == -1) { // Check for open() failure
puts("ERROR: Unable to open file using open()");
exit(0);
}

file = fdopen(file_descriptor, "r+"); // Use descriptor

if (file == NULL) {
puts("ERROR: Unable to open file using fdopen()");
fclose(file);
exit(0);
}

// fscanf(file, "%c", stdout); // Hangs
// fgets(buffer, sizeof(buffer), file); // Hangs
printf("%c", fgetc(file)); // Hangs

fclose(file);

return 0;
}

Answer

The expression

file_descriptor = open(argv[1], O_RDWR) == -1

does not work as you expect it to, because the equality operator == have higher precedence than the assignment operator. That means the expression is more like

file_descriptor = (open(argv[1], O_RDWR) == -1)

which means your file_descriptor will be either 0 or 1 depending on how the comparison went.

You need to use parentheses for the assignment:

(file_descriptor = open(argv[1], O_RDWR)) == -1
Comments