如何在rename()中使用文件路径?

huangapple go评论58阅读模式
英文:

How to use filepaths with rename()?

问题

I use the rename() function, but it renames files only in the program directory. How can I point her to a file outside the program folder?

我使用rename()函数,但它只能重命名程序目录中的文件。如何将其指向程序文件夹之外的文件?

I tried to give an input string like
"/home/user/folder/file.txt"
"~/folder/file.txt"
But it still gave an error that the file was not found.

我尝试提供类似的输入字符串
"/home/user/folder/file.txt"
"~/folder/file.txt"
但它仍然报错文件未找到。

#include<stdio.h>
#include<errno.h>

int main(){
    char oldn[256]="~/testfolder/oldname.txt";
    char newn[256]="~/testfolder/newname.txt";
    int ret = rename(oldn, newn);

    if(ret!=0){
        fprintf(stderr, "Cant rename! Error: %d\n", errno);
        perror("error msg");
    }
}
英文:

I use the rename() function, but it renames files only in the program directory. How can I point her to a file outside the program folder?

I tried to give an input string like
"/home/user/folder/file.txt"
"~/folder/file.txt"
But it still gave an error that the file was not found.

#include<stdio.h>
#include<errno.h>

int main(){
    char oldn[256]="~/testfolder/oldname.txt";
    char newn[256]="~/testfolder/newname.txt";
    int ret = rename(oldn, newn);

    if(ret!=0){
        fprintf(stderr, "Cant rename! Error: %d\n", errno);
        perror("error msg");
    }
}

答案1

得分: 1

"getenv("HOME")" 正在为我工作,以及其他路径如 "home/user/folder/file.txt"。

英文:

Well getenv("HOME") Is working for me, and other paths like "home/user/folder/file.txt".

huangapple
  • 本文由 发表于 2023年6月6日 16:11:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76412627.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定