0

As the title implies I am trying to open a text file in the same directory as of the program I'm running. Here is the code I am using:

int main(int argc, char *argv[]){

    FILE *filePtr;
    filePtr = fopen("something.txt", "r");
    if (filePtr == NULL){
      printf("Oh dear, something went wrong with read()! %s\n", strerror(errno));
      return 1;
    }

  return 0;
}

This prints out:

Oh dear, something went wrong with read()! No such file or directory

I have also tried using fopen("./something.txt", "r"); but the same thing happened.

NoHoly
  • 23
  • 4
  • You are indeed working with minix? – Ctx Dec 28 '19 at 18:30
  • 1
    A relative path is not relative to the program, but to the current working directory to the program. Are you sure that the cwd is identical to the location of the file? You could try to print it first, with `printf("CWD: %s\n", getcwd());` – Ctx Dec 28 '19 at 18:32
  • Thank you, will try! And yes, I am required to do this the minix OS... – NoHoly Dec 28 '19 at 18:33
  • Sometimes if you use Avast antivirus it doesn't allow it to open file from the same directory as of the program you're running. So i can suggest you, if you using it, try to disable it, and than open. – Poszer Dec 28 '19 at 18:35
  • @Poszer I don't think Avast is available for Minix :-D – hyde Dec 28 '19 at 18:40
  • Didn't saw it Minix, sorry. – Poszer Dec 28 '19 at 18:46
  • @Ctx it prints ```CWD: /``` so... do I need to change anything? I tried with ```/something.txt``` now but it still doesnt work. – NoHoly Dec 28 '19 at 18:47
  • 1
    And does that file exist at that location? (Does `ls /` show it?) – Shawn Dec 28 '19 at 18:51
  • Ohhh it does not... but now I am a bit confused. I compile the program in a certain directory and when running it, it goes to a different directory? I think I'm missing something. – NoHoly Dec 28 '19 at 18:55
  • 1
    "*with read()*" err, what? There is no call to `read()` within the code you show. – alk Dec 29 '19 at 11:13
  • 1
    regarding: ` printf("Oh dear, something went wrong with read()! %s\n", strerror(errno));` Error messages should be output to `stderr`, not `stdout`. Strongly suggest: `fprintf( stderr, "Oh dear, something went wrong with fopen()! %s\n", strerror(errno));` – user3629249 Dec 29 '19 at 13:19

1 Answers1

0

1> Go in directory where program + executable is present. Execute from there. 2> If not then there is probability of some permission related issue. try using [ int access(const char *pathname, int mode)] API if(access("something.txt", R_OK) == 0)

then only go ahead. This will check whether you have read permission or not. If you have root permission then only try to open. If not provide sufficient permission.

UpendraG
  • 29
  • 3