Home > Blockchain >  read() taking input from stdin instead of file descriptor
read() taking input from stdin instead of file descriptor

Time:11-13

I have a C program that needs to take in two arguments from bash: A filename and a character. Passing a valid file opens it without issue, and yet when I call read() on the file description the input is read from stdin. This seemingly even occurs before any other code runs, as putting a printf at the very beginning of main() will only output after input is taken from stdin.

Passing invalid filenames or wrong amounts of arguments are caught correctly, and this issue still occurs if I hardcode the file name.

The file is read like this:

// Open the file and quit if an error occurs
if ((fd = open(argv[1], O_RDONLY) < 0)) {
    printf("Error opening file %s\n", argv[1]);
    return 1;
}

// Read the file into charBuffer and exit on error
if ((charsRead = read(fd, charBuffer, 2048)) < 0) {
    printf("Error reading contents of file.\n");
    return 1;
}

printf("%s\n", charBuffer);

Why is my program reading input from stdin instead of grabbing it from the file? Why does this happen before any other output from the program?

CodePudding user response:

Precedence issue.

fd = open(argv[1], O_RDONLY) < 0

means

fd = ( open(argv[1], O_RDONLY) < 0 )

It should be

( fd = open(argv[1], O_RDONLY) ) < 0

CodePudding user response:

You have parenthesises in the nonsense place. You have silenced the compiler warning making your code extremely error prone. Instead of:

if ((fd = open(argv[1], O_RDONLY) < 0))

do

fd = open(argv[1], O_RDONLY);
if (fd < 0)
  • Related