Concatenating a file by getting the full path in C

Using C, I try to combine the names of the files in the directory with their paths so that I can call stat () for each, but when I try to do this with strcat inside the loop, it combines the previous file name with the next, It changes argv [1] during the cycle, but I have not worked with C for a long time, so I am very confused ...

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>

int main(int argc, char *argv[]) {
 struct stat buff;

 int status;

 if (argc > 1) {
  status = stat(argv[1], &buff);
  if (status != -1) {
   if (S_ISDIR(buff.st_mode)) { 
     DIR *dp = opendir(argv[1]);
     struct dirent *ep;
     char* path = argv[1];
     printf("Path = %s\n", path);

     if (dp != NULL) {
       while (ep = readdir(dp)) {
       char* fullpath = strcat(path, ep->d_name);
       printf("Full Path = %s\n", fullpath);
     }
     (void) closedir(dp);
   } else {
      perror("Couldn't open the directory");
   }
 }

  } else {
   perror(argv[1]);
   exit(1);
  }
 } else {
   perror(argv[0]]);
                exit(1);
 }

 return 0;
}
+3
source share
4 answers

You must not change argv[i]. Even if you do, you will only have one argv[1], so it strcat()will continue to add everything that you had before.

. , / . .

, while:

size_t arglen = strlen(argv[1]);

while:

/* + 2 because of the '/' and the terminating 0 */
char *fullpath = malloc(arglen + strlen(ep->d_name) + 2);
if (fullpath == NULL) { /* deal with error and exit */ }
sprintf(fullpath, "%s/%s", path, ep->d_name);
/* use fullpath */
free(fullpath);
+9

, ? , , , , .

char path[1024] ;   // or some other number
strcpy( path, argv[1] );
// then separator
strcat( path, "/" ) ; // or "\\" in Windows
strcat( path, ep->d_name);

se strncat ..,

+1

argv [1] strcat'ing ( - ), undefined. argv [1] :

char path[1000];   // or some suitable size;
strcpy( path, argv[1] );
0

,

char* fullpath = strcat(path, ep->d_name);

path. ,

char* fullpath = calloc(strlen(path) + strlen(ep->d_name) + 1);
strcat(fullpath, path);
strcat(fullpath, ep->d_name);
/* .. */
free(fullpath);
0
source

Source: https://habr.com/ru/post/1730356/


All Articles