0

I need to open a file, providing the full path. I used the function fopen to open the file, this works

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

int main () {

FILE *file;

file = fopen("C:\\Users\\Edo\\Desktop\\sample.docx","rb");

if (file == NULL) {
printf("Error");
exit(0);
}

return 0;
}

but what i really need is to let the user choose which file he wants, however this code does not work .

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

 int main () {

 FILE *file;

 char path[300];

 printf("Insert string: ");
 fgets(path, 300, stdin);

 file = fopen(path,"rb");

 if (file == NULL) {
 printf("Error");
 exit(0);
 }

 return 0;
 }

I tried as input:

C:\Users\Edo\Desktop\sample.docx

C:\\Users\\Edo\\Desktop\\sample.docx

C:/Users/Edo/Desktop/sample.docx

C://Users//Edo//Desktop//sample.docx

none of them works

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • 7
    I assume when the user enters the full path, it's terminated in a newline. According to the `fgets` documentation: *If a newline is read, it is stored into the buffer.* You'll need to **[get rid of the newline character at the end of the line](https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input)** to get a valid file name. – lurker Feb 02 '18 at 21:26
  • 1
    if you want to explore why this is not working (although @lurker is probably correct) use sysinternals procmon, it will show you all the file operations performed by your program and why they failed – pm100 Feb 02 '18 at 21:29
  • By the way, you might wish to consider replacing `printf("Error");` with something line `perror(path)` – cdarke Feb 02 '18 at 22:56

2 Answers2

4

fgets leaves the newline on the end of your string. You'll need to strip that off:

path[strlen (path) - 1] = '\0';

You'll need to #include <string.h> for this too.

Perette
  • 821
  • 8
  • 17
0

Thanks @lurker, he told me what was the problem, I fixed the code this way

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

int main () {

FILE *file;

char path[300];

printf("Insert string: ");
fgets(path, 300, stdin);

strtok(path, "\n");
file = fopen(path,"rb");

if (file == NULL) {
printf("Error");
exit(0);
}

return 0;
}