[英]How to move file in Linux using C++
如何在Linux中使用C ++程序将文件从一个位置移动到另一位置? 我已经编写了一个程序来执行此操作,该程序可以运行,但是当我尝试将文件移动到其他目录时,它不会移动文件,但我从cout语句中得到了错误消息。 当我尝试重命名文件时,使用新名称将其移动到同一目录即可。 如何修复我的代码,使其能够将文件移动到另一个目录?
这是我编写的代码:
#include <iostream>
#include <stdio.h>
using namespace std;
int main ()
{
int result=1;
char oldname[500];
char newname[500];
cout << "Enter the name of a file you want to move (include directory structure)";
cin >> oldname;
cout << "Enter the new location (include directory structure)";
cin >> newname;
result = rename( oldname , newname );
if ( result == 0 )
cout << "File successfully moved" << endl;
else
cout << "Error moving file" << endl;
return 0;
}
编辑:我在代码中添加了错误,并且显示的错误消息是“错误移动文件:没有这样的文件或目录”,即使我尝试将其移动到的目录确实存在并且具有创建和删除文件的权限。
您的代码在大多数情况下都可以使用。 但是您忽略了一些重要的事情,在这种情况下,它会崩溃:
oldname
和newname
使用rename()
无法在文件系统之间移动,因此必须这样做(并包含iostream
)
ifstream ifs(oldname, ios::in | ios::binary); ofstream ofs(newname, ios::out | ios::binary); ofs << ifs.rdbuf(); remove(oldname);
在remove()
之前,您的总磁盘空间会少一点。
newname
的文件系统上的可用空间会缩小,而这是您拥有的可用空间,因为否则您将无法在此处移动文件 oldname
和newname
在同一个文件系统上,并且您确实担心这种暂时的丢失,那么请检查您是否将使用同一个文件系统,并毕竟使用rename()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.