Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

read() taking input from stdin instead of file descriptor

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// 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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading