1

I'm reading the path of some file from a file given as arguments to my application. Each path is written on a line. I have problem with the last path which give me this error:

Cannot open C:\Users\Utente\Desktop\find\try1.txtl¹v

Here's my code:

    struct filePath{
        char path[255];
        int fileOccurences;
    };

    struct filePath fPath[2];
    char currentLine[255];
    char path[255];
    char word[30];
    int i, ch;
    int k = 0;
    FILE * fInput = fopen(argv[1], "r"); 
    if(fInput == NULL){ //check sull'apertura del file
        fprintf(stderr, "Cannot open %s, exiting. . .\n", argv[1]);
       exit(1);
    }

    while(!feof(fInput)){
        for (i = 0; (i < (sizeof(path)-1) && ((ch = fgetc(fInput)) != EOF) && (ch != '\n')); i++){
            fPath[k].path[i] = ch;
        }
        FPath[k].path[i] = '\0';
        k = k + 1;
    }
    fclose(fInput);
    for(int j = 0; j<2; j++){
        FILE * fp = fopen(fPath[j].path, "r"); 
        if(fp == NULL){ 
            fprintf(stderr, "Cannot open %s, exiting. . .\n", fPath[j].path);
            exit(1);
        }
    }

I have upload only the interested part of the program, this isn't how i exactly wrote my code. So, someone know how can i solve this problem and cancel these character "l¹v". Thank you.

YPD
  • 187
  • 13
  • How are you running your program? Can you give an example of what you type on the command line? Also, can you fix the errors in your code. I cannot compile and run it as it is in this question, primarily because you have no `main()`. – Code-Apprentice Nov 05 '19 at 23:00
  • Is this message coming because `fInput` is NULL or because `fp` is NULL? – KamilCuk Nov 05 '19 at 23:03
  • Also, change the error message. In that way, we know where the error occurred. – Akshay G Bhardwaj Nov 05 '19 at 23:04
  • Are you reading the paths in a `while (!feof(Input))` loop? Don't do that.https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – William Pursell Nov 05 '19 at 23:06
  • In the error message, don't just say "Cannot open file". Give the reason. `man perror` and `man strerror` – William Pursell Nov 05 '19 at 23:08

1 Answers1

3

You read the file names character by character into fPath[k].path[i], then set path[i] to nul after the loop. But fPath[k].path and path are not the same variable, so you haven't null-terminated fPath[k].path[i]

FredK
  • 4,094
  • 1
  • 9
  • 11