Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program hangs after opening file with open and fdopen [duplicate]

Tags:

c

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;
}
like image 765
Insane Avatar asked Dec 01 '22 16:12

Insane


2 Answers

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
like image 199
Some programmer dude Avatar answered Dec 05 '22 05:12

Some programmer dude


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.

like image 25
mkj Avatar answered Dec 05 '22 07:12

mkj