0

I am trying to save the names and sizes of files in a directory in this way:

For the first file everything is fine. On the second file it says it can't determine the file path. This is because at the end I clear the "mainPath", but then when the reassignment takes place the variable "path" is also cleared.

if ((directory = opendir(path)) != NULL)
{
    while((d = readdir(directory)) != NULL)
    {
        if(strcmp(d->d_name, "..")!=0 && strcmp(d->d_name, ".")!=0)
        {
            strcpy(fileSpec[i].fileName, d->d_name);
            char *mainPath = path;
            strcat(mainPath, d->d_name);

            fileSpec[i].fileSize = stat_filesize(mainPath);

            printf("\t%s ---> %ld\n", fileSpec[i].fileName, fileSpec[i].fileSize);
            i++;
            strcpy(mainPath, "");
        }
    }
    closedir(directory);
}

There's something I don't understand. Why is it that when I use strcpy(mainPath, ""); only the variable "mainPath" is not cleaned?

This is because I need to pass the path as an argument.

Difettoso
  • 51
  • 1
  • 1
  • 10
  • 2
    `path` and `mainPath` are the same string. How much do you know about pointers? – user253751 Apr 13 '21 at 16:10
  • how can I do this? Without affecting path? – Difettoso Apr 13 '21 at 16:15
  • store the mainPath string in a different variable? – user253751 Apr 13 '21 at 16:18
  • 1
    @Difettoso You would have to allocate a sufficiently large string for `mainPath`, `strcpy` `path` to it, and `strcat` `d->d_name` to it. But I suggest you first follow a tutorial on pointers. – Emanuel P Apr 13 '21 at 16:23
  • 1
    You should be aware of [`stat()` error "no such file or directory" when file name is returned by `readdir()`](https://stackoverflow.com/questions/5125919/stat-error-no-such-file-or-directory-when-file-name-is-returned-by-readdir) and related questions. If the original `path` is not `.`, you are likely to run into problems. – Jonathan Leffler Apr 13 '21 at 16:43
  • really bad mistake sorry, I solved it this way `char *mainPath; strcpy(mainPath, path);` whitout `strcpy(mainPath, "");` – Difettoso Apr 13 '21 at 17:31
  • As long as `mainPath` was pointing somewhere valid, that should be OK. – Jonathan Leffler Apr 13 '21 at 20:50

0 Answers0