使用C在Linux上移动文件 [英] Moving a file on Linux in C

查看:449
本文介绍了使用C在Linux上移动文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 平台:Debian Wheezy 3.2.0-4-686-pae
  • 编译器:GCC(Debian 4.7.2-5)4.7.2(Code :: Blocks)

我想将文件从一个位置移动到另一位置.移动到不同的驱动器或文件系统没有什么复杂的.我知道执行此操作的标准"方法是简单地复制文件,然后删除原始文件.但是我想要某种方式来保留文件的所有权,模式,上次访问/修改等.我假设我必须先复制文件,然后再编辑新文件的所有权,模式等,但是我不知道该怎么做.

I want to move a file from one location to another. Nothing complex like moving to different drives or to different file systems. I know the "standard" way to do this would be simply copying the file and then removing the original. But I want some way of preserving the file's ownership, mode, last access/modification, etc. . I am assuming that I will have to copy the file and then edit the new file's ownership, mode, etc. afterwards but I have no idea how to do this.

推荐答案

如果不能使用重命名(2)系统调用(例如,由于源和目标位于不同的文件系统上),您必须使用 read(2) write(2)(使用几千字节的缓冲区), open(2) utime(2).您可能还想使用 getxattr(2)复制属性, setxattr(2) sendfile(2),根据 David C. Rankin 的评论.

If you cannot use the rename(2) syscall (e.g. because source and target are on different filesystem), you have to query the size, permission and other metadata of the source file with stat(2); copy the data using read(2), write(2) (using a buffer of several kilobytes), open(2), close(2) and the metadata using chmod(2), chown(2), utime(2). You might also care about copying attributes using getxattr(2), setxattr(2), listxattr(2). You could also in some cases use sendfile(2), as commented by David C. Rankin.

如果源和目标位于不同的文件系统上,则无法使迁移成为原子操作并避免出现竞争情况(因此,请使用

And if the source and target are on different filesystems, there is no way to make the move atomic and avoid race conditions (So using rename(2) is preferable when possible, because it is atomic according to its man page). The source file can always be modified (by another process) during the move operations...

因此,移动文件的一种实用方法是先尝试进行重命名(2),如果以EXDEV失败(当 oldpath newpath 不在同一挂载文件系统上),则需要复制字节和元数据.几个库提供了执行此操作的功能,例如Qt QFile :: rename .

So a practical way to move files is to first try doing a rename(2), and if that fails with EXDEV (when oldpath and newpath are not on the same mounted filesystem), then you need to copy bytes and metadata. Several libraries provide functions doing that, e.g. Qt QFile::rename.

阅读高级Linux编程了解更多信息(并尝试strace一些mv命令以了解其操作).该书可免费合法下载(因此您可以在网上找到几本).

Read Advanced Linux Programming for more (and also try to strace some mv command to understand what it is doing). That book is freely and legally downloadable (so you could find several copies on the Web).

这篇关于使用C在Linux上移动文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆