Question

Doing analog of unix func "cp" on c and I have trouble with realisation:

struct stat fsd;
stat(argv[argc - 1], &fsd);

if ((fsd.st_mode & S_IFMT) == S_IFDIR) {

    unsigned int i;

    for (i = src; i < argc - 1; i++) {

        char *xpath = strcat(argv[argc - 1], "/");
              xpath = strcat(argv[argc - 1], argv[i]);

        if (cpf(argv[i], xpath) == 0) {

            printf( "%s -> %s\n", argv[i], xpath);
        }

    }
}

Example command: ./cp f1 f2 f3 f4 dir
Where: f* - files and dir - directory. So, files need to be copied into dir, but I can't create correct path for the dir.

Output:

f1 -> dir/f1
f2 -> dir/f1/f2
f3 -> dir/f1/f2/f3
f4 -> dir/f1/f2/f3/f4

But I need:

f1 -> dir/f1
f2 -> dir/f2
f3 -> dir/f3
f4 -> dir/f4

Really have no idea how to fix it :(

Was it helpful?

Solution

The main problem, of many, that the two

xpath = strcat(argv[argc - 1], ...

concatenate to argv[argc - 1] additional text.

I am certain you are thinking that strcat() concatenates 2 strings and supplies the combine result as the answer without affecting the inputs. It does not do this, rather, it appends the 2nd parameter to the 1st, returning the first parameter.

Re-write your code to create a buffer workspace.

char xpath[1000];
strcpy(xpath, argv[argc - 1]);
strcat(xpath, "/");
strcat(xpath, argv[i]);

BTW, the sizeof() xpath could be MAXPATHLEN or some other system constant, but that is another question. See #include limits.h.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top