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;
}
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
To add to the other answer. It's "hanging" because the bug causes it actually to read standard input (file descriptor 0). Try typing something and it will read it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With