YPD
YPD

Reputation: 207

Problem while opening a file because of weird characters on the file path

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.

Upvotes: 1

Views: 284

Answers (1)

FredK
FredK

Reputation: 4084

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]

Upvotes: 3

Related Questions