C语言中文件可以自行移动吗?

发布于 2025-01-17 16:09:55 字数 1468 浏览 3 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

幽蝶幻影 2025-01-24 16:09:55

下面的代码“复制”到新目的地,并在终止后删除。基本上,代码在指定的位置进行了新的条目(硬链接),并删除当前的位置(从调用目录)。由于不涉及副本和删除,因此将保留文件的内容。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <libgen.h>

int main(int argc, const char *argv[])
{   
    //current filepath (dir + name)
    const char* file_path = argv[0];

    //extract filename component (needed to append to newdir)
    char* file_name_ = strdup(file_path);
    char* file_name = basename(file_name_);

    //make new path name
    char* new_dir = "<put your destination here - with no slash ('/') at the end>";
    size_t new_path_len = strlen(new_dir) + strlen(file_name) + 2; //two extra bytes: '/' + '\0'
    char new_path[new_path_len];
    snprintf(new_path, new_path_len, "%s/%s", new_dir, file_name);

    //make a new name for a file (hardlink)
    link(file_path, new_path);
    //delete a name and possibly the file it refers to
    unlink(file_path);

    //cleanup
    free(file_name_);

    return 0;
}

提示:强烈建议对link的文档进行仔细研究(尤其是错误部分)。

参考:

basename - parse parse pathname组件
link - 为文件
创建一个新名称
unlink - - 删除一个名称,可能是指它所转到的文件

The code below "copies" itself to a new destination and gets deleted after termination. Basically, the code makes a new entry (hardlink) at the specified location and removes the current one (from the calling directory). The contents of the file will be preserved, since there is no copy and deletion involved.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <libgen.h>

int main(int argc, const char *argv[])
{   
    //current filepath (dir + name)
    const char* file_path = argv[0];

    //extract filename component (needed to append to newdir)
    char* file_name_ = strdup(file_path);
    char* file_name = basename(file_name_);

    //make new path name
    char* new_dir = "<put your destination here - with no slash ('/') at the end>";
    size_t new_path_len = strlen(new_dir) + strlen(file_name) + 2; //two extra bytes: '/' + '\0'
    char new_path[new_path_len];
    snprintf(new_path, new_path_len, "%s/%s", new_dir, file_name);

    //make a new name for a file (hardlink)
    link(file_path, new_path);
    //delete a name and possibly the file it refers to
    unlink(file_path);

    //cleanup
    free(file_name_);

    return 0;
}

Hint: careful study of the documenation to link is highly recommended (especially the ERRORS section).

References:

basename - parse pathname components
link - make a new name for a file
unlink - delete a name and possibly the file it refers to

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文