The program freezes after opening a file with open and fdopen

I use open()c O_RDWR, and then using the handle in fdopen()c "r+". I check that the file exists first with access(), and check for a open()return of -1, then check that it is FILE *fpinstalled from fdopen()not NULL.

Now, when I use any function, such as fgets()or fgetc()with fp, the program freezes in my terminal. I do not receive 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;
}
+4
source share
2 answers

Expression

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

, , == precedence, . ,

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

, file_descriptor 0, 1 , .

:

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

. "", ( 0). -, .

+6

Source: https://habr.com/ru/post/1659585/


All Articles