Search code examples
cfopen

fopen won't open file, providing the full path via fgets


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


Solution

  • 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.