0

I have this code that's supposed to read from a text file and print its content but I keep getting "Unable to open file."

#include <stdio.h>
#include <string.h>

#define MAX 4000
int main(void)
{
    FILE *bkptr;
    char buffer[MAX];

    bkptr = fopen("defoe-robinson-103.txt", "r");
// If file dow not open
    if (bkptr == NULL) {
        puts("Unable to open file.");
    }
// If file open
    else {
// Read each line form file until EOF
        while (fgets(buffer, MAX, bkptr)) {
// Print the line
            puts(buffer);
        }

// Close the file
        fclose(bkptr);
    }
}
undur_gongor
  • 15,657
  • 5
  • 63
  • 75
jay
  • 1
  • 4
    Your program is probably not running in the right directory — that is, the current directory is likely not the directory containing the file. But you can find out more: when file opening fails, always print out the error reason by calling `perror()` or printing the result of calling `strerror(errno)`. – Steve Summit Dec 01 '21 at 19:01
  • It means the file is not in the current process directory. – stark Dec 01 '21 at 19:01
  • 1
    Possible duplicates: [C Program can't open file](https://stackoverflow.com/questions/7939018), [Cannot open a file in C](https://stackoverflow.com/questions/59766930) – Steve Summit Dec 01 '21 at 19:04
  • `Unable to open file` is not a particularly useful error message. As @SteveSummit points out, you can get a more useful error message with `strerror` or `perror`. But even bad error message belong on stderr: `fputs("error message\n", stderr);` – William Pursell Dec 01 '21 at 19:07
  • Avoid hardcoding filenames. Either pass the filename as the first argument to the program (that's what `int argc, char **argv` are for) or take the filename as input. That way you don't need to recompile your program just to read from a different filename. Reasonable example of [taking the filename as an argument](https://stackoverflow.com/a/55703813/3422102). – David C. Rankin Dec 01 '21 at 19:11

0 Answers0