Question

Part of my program needs to get a file path from the user and then move and rename said file.

If I use the relative path like this:

#include <stdio.h>

int main() {
    int check;
    char oldname[] = "images//test_1.jpg";
    char newname[] = "images//test//test_2.jpg";
    check = rename(oldname, newname);
    if (check == 0)
        puts("Success");
    else
        perror("Failed");
    return 0;
}

It works perfectly.

But if I try to use the absolute path like this:

char oldname[] = "c://path//images//test_1.jpg";
char nername[] = "c://path//images//test//test_2.jpg";

it fails and says "Failed: No such file or directory"

I am sure its some silly mistake but no matter how many times I double check my file path and code I can't figure it out. Any suggestions would be greatly appreciated.

Oh and if it makes any difference I'm working in linux.

Was it helpful?

Solution

If it is running on the linux server, you need to use the path on the linux server. You can use pwd to print the working directory (which will give you the absolute path that you are currently in). Also you can use a relative path with .. to go up a directory. For example your directory structure may be like this

code/
    main.cpp
    main.h
    a.out

images/
    yourimage.png

So you could do:

$ pwd
/home/user/code

and then your absolute path to the image would be

/home/user/images/yourimage.png

Or you could use a relative path from the code directory

../images/yourimage.png
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top