0

I see a few similar questions in C, but they do not answer my question.
Consistent perror is Error: No such file or directory. User input is aFile.txt and I confirm this file exists in the same directory as the program.
If I manually change:

input_file = fopen(path, "r");<br/>

to:

input_file = fopen(".\aFile.txt", "r");<br/>

IT WORKS...
Also, printf("path = %s\n", path); prints .\aFile.txt
which leads me to believe my concatenation is OK. What am I doing incorrectly?

   char path[25] = "./";
   char filename[21];
   printf("Enter filename, max 20 characters: ");
   fgets(filename, 20, stdin);
   strcat(path, filename);
   strtok(path, "\n"); // FIXED THE ISSUE BY REMOVING THE trailing '\n'
   printf("path = %s\n", path);

   FILE * input_file;
   input_file = fopen(path, "r"); // fopen(".\aFile.txt", "r") works!!!
   if (input_file == NULL)
        perror("Error");
   else {
        loader(list, input_file);
        fclose(input_file);
        printf("list loaded from file succesfully.\n");
   }
RigidBody
  • 656
  • 3
  • 11
  • 26
  • 2
    Most likely you have the new line character in your path variable (fgets includes it). Remove trailing whitespace and it should work – TheGreatContini May 11 '16 at 20:54
  • 2
    [man fgets](http://linux.die.net/man/3/fgets): "If a newline is read, it is stored into the buffer." – kaylum May 11 '16 at 20:55
  • 1
    Well, certainly is a duplicate... unless you didn't know about the fgets \n issue... :p – RigidBody May 11 '16 at 21:09

2 Answers2

3

fgets will include the newline character, so most likely this is what's killing it. Remove the newline at the end and it should work.

TheGreatContini
  • 6,429
  • 2
  • 27
  • 37
2

It's the new line being read. A good way to see this is to print the filename with a leading and trailing ":":

printf("path = :%s:\n", path);

What is printed is:

Server:junk Username$ ./a.out 
Enter filename, max 20 characters: test.txt
path = :./test.txt
:
Error: No such file or directory

Note the second ":" is on a new line.

JBM
  • 105
  • 8