将文件从一个目录移动到另一个目录

将文件从一个目录移动到另一个目录

本文介绍了将文件从一个目录移动到另一个目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将所有文件从 test1 复制到 test2.代码编译但没有任何反应.

I would like to copy all files from test1 into test2. The code compiles but nothing happens.

#include <iostream>
#include <stdlib.h>
#include <windows.h>

using namespace std;

int main()
{
    string input1 = "C:\\test1\\";
    string input2 = "C:\\test2\\";
    MoveFile(input1.c_str(), input2.c_str());
}

我正在考虑 xcopy 但它不接受预定义的字符串.有解决办法吗?

I was considering xcopy but it would not accept a pre defined string. Is there a work around?

推荐答案

std::string GetLastErrorAsString()
{
    //Get the error message, if any.
    DWORD errorMessageID = ::GetLastError();
    if (errorMessageID == 0)
        return std::string(); //No error message has been recorded

    LPSTR messageBuffer = nullptr;
    size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);

    std::string message(messageBuffer, size);

    //Free the buffer.
    LocalFree(messageBuffer);

    return message;
}
int main()
{
    string input1 = "C:\\test1\\";
    string input2 = "C:\\test2\\";
    if (!MoveFile(input1.c_str(), input2.c_str()))
    {
        string msg = GetLastErrorAsString();
        cout << "fail: " << msg << endl;
    }
    else {
        cout << "ok" << endl;
    }
    system("pause");
}

您的代码对我有用,您可能需要在项目属性中将字符集设置为 use multi-byte character set.如果没有,请向我们提供错误信息.检查您是否拥有 C: 上的写权限.检查 C: 中是否已经存在 test2 文件夹(或者 C: 中是否没有 test1 文件夹).

Your code works for me, you may have to set the character set to use multi-byte character set in your project properties.If not, provide us with the error.Check if you have the write rights on C:.Check if there already is a test2 folder in C: (or if there is not a test1 folder in C:).

这篇关于将文件从一个目录移动到另一个目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 16:06