user1827612
user1827612

Reputation:

Simple Linux programming: File read not going well?

I am trying to write a simple program to read from a file and print it in the terminal. But the program hangs after opening the file. if I remove the reading part, it works well. I don't know what is going wrong. Can somebody help? please!

#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
  int fd,bytes;
  char buffer[10];
  char path[ ] = "file";

  if(fd = open(path, O_RDONLY) < 0) {
    perror("open");
    exit(EXIT_FAILURE);

  } else {
    printf("opened %s\n", path);
  }

  do {
    bytes = read(fd,buffer,10);
    printf("%d", bytes);
  } while( bytes > 0);

  if(close(fd) < 0) {
    perror("close");exit(EXIT_FAILURE);
  } else{
    printf("closed %s\n", path);
  }
  exit(EXIT_SUCCESS);
}

Upvotes: 1

Views: 1367

Answers (2)

pbhd
pbhd

Reputation: 4467

So, first your program as Mat explained assigns 0 to fd if "file" exists. The consecutive read's read from stdin. This can be interpreted as "hanging", but in reallity your program just reads from stdin, and your printf's are not shown, because there is no \n at the end. If you change it to

do {
  bytes = read(fd,buffer,10);
  printf("%d", bytes);
  fflush (stdout);
} while( bytes > 0);

Then you will see what happens... Cheers.

Upvotes: 2

Mat
Mat

Reputation: 206669

if(fd = open(path, O_RDONLY) < 0) {

This is parsed as:

if(fd = (open(path, O_RDONLY) < 0)) {

Which assignes 0 or 1 to fd. You need an extra set of parens:

if((fd = open(path, O_RDONLY)) < 0) {

Or better, write it in two lines.

fd = open(...);
if (fd < 0) {

Upvotes: 4

Related Questions