-2

I have the following code that gets the filepath from another module, opens the file and reads the content. The file is opening , but read fails with error: Bad file number. I then inserted a write command after open, which works, but read still fails.Can someone please tell me why read isnt working? Also , Im puzzled about why write() even works when im opening the file in R_ONLY mode.

          char* file_content = (char*) malloc (1024);
          int fd = open(filepath,"O_RDONLY");
          printf("I have attempted open file \n");
          fflush(stdout);
          bzero(file_content, 1024*sizeof(char));
          if(fd <= 0) { //open failed
            file_content = "Error opening file";
            printf("The error number is %d\n", errno);
            fflush(stdout);
          }
          else
          {
             if(write(fd, "hello", 5)<0){
                printf("write failed");
                fflush(stdout);
              }
            if(read(fd, file_content,1023) < 0){
                printf("Error! Read file as %d\n",errno);
                fflush(stdout);
            }
          }

Output is Error! Read file as 8. 8=Bad file number. Any help please?

crypto9294
  • 171
  • 2
  • 14
  • 5
    `open(filepath,"O_RDONLY");` - you are in the most serious need of reading the man page for `open()`. –  Apr 29 '13 at 20:15
  • `(char*) malloc (1024)` - you are in the most serious need of reading [the reasoning in this answer](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858) about the harmful nature of that superfluous cast. –  Apr 29 '13 at 20:17
  • 1
    How did that even compile in the first place?! – JustSid Apr 29 '13 at 20:18
  • @JustSid no reason it wouldn't compile. it will just use the address of the string as an `int` while looking for the open flags. c is very 'forgiving' – cmd Apr 29 '13 at 20:24
  • -wall is your friend. – Michael Dorgan Apr 29 '13 at 21:00

1 Answers1

3

The problem is

open(filepath,"O_RDONLY");

should be

open(filepath, O_RDONLY);

currently it is using the address of the string literal as the integer for the open flags.

cmd
  • 5,754
  • 16
  • 30