0

I need to move from the directory I am working on and then verify if a .txt file exists or not. The name of the .txt file is the int key value received as an argument.

What I tried to do was cast the int value into char and then append .txt. Then use this new string to try and open the file.

However, even if the file does exist within the directory, I still get "File doesnt exist".

What do I need to change in order for it to work?

    char k[10];
    char app[4] = ".txt";
    int status;

    // Change directory where we work.
    if(chdir("txtFiles") == -1){
        perror("Error while changing directories.");
        return -1;
    }

    // Convert key to string.
    snprintf(k, 10, "%d", key);
    strncat(k, app, 4);
    printf("%s\n", k);

    // Open the file.
    if((status = open(k, O_RDONLY)) == -1){
        printf("File DOESNT exist.\n");
    } else {
        printf("File exists.\n");
    }

    return 0;
}
ICS
  • 87
  • 3
  • for me your code says 'file does not exist' once I fixed the length of app – pm100 Mar 14 '23 at 23:37
  • @pm100 My bad, it does say "file doesnt exist", just edited it. – ICS Mar 14 '23 at 23:38
  • ok - then the fix suggested below is what you need. Also check errno to make sure it realy is 'file doesnt eist' and not something like 'permission denied' – pm100 Mar 14 '23 at 23:51
  • When the whole code is shown (the `int main(…)` line was hidden after the triple back-ticks before), then one of the main problems is that you've shown a wholly non-standard and unsupported variant signature for `main()`. See [What should `main()` return in C and C++](https://stackoverflow.com/q/204476/15168) for the details of what is valid. – Jonathan Leffler Mar 15 '23 at 00:01

1 Answers1

2

app is too short to accommodate ".txt". It has to be char app[5] = ".txt" (or, better, char app[] = ".txt"; — computers are good at counting).

You can do this much more easily in one snprintf call:

    snprintf(k, 10, "%d.txt", key);

or if the extension is not always the same

    snprintf(k, 10, "%d%s", key, app);

strncat is not needed anymore.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
0___________
  • 60,014
  • 4
  • 34
  • 74
  • 1
    does not answer the question tho – pm100 Mar 14 '23 at 23:29
  • 1
    1) Probably best to point out the cause of the problem with the `strncat` (and the sizing of `app`), 2) The second argument should be `10`, not `9` (`snprintf`, unlike some of the others, includes the terminating NUL in the count) and 3) They likely need to increase the size of `k` (unless `key` is guaranteed to be pretty small, the limit to nine characters of actual filename means any number with six digits or more won't fit, and the `.txt` will get truncated). – ShadowRanger Mar 14 '23 at 23:32
  • @pm100 it is UB. Hard to say what else was affected. – 0___________ Mar 14 '23 at 23:41