Concatenating file with path to get full path in C

后端 未结 4 1087
执笔经年
执笔经年 2021-01-03 07:57

Using C, I\'m trying to concatenate the filenames in a directory with their paths so that I can call stat() for each, but when I try to do using strcat inside the loop it co

4条回答
  •  隐瞒了意图╮
    2021-01-03 08:46

    The problem is that the line

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

    keeps appending the name of the current file to path. Try creating a new string for the full path each time, like

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

提交回复
热议问题