2016-07-20 5 views
0
 wstring path = L"C:\\Users\\oneworduser\\Desktop\\trash"; 
     LPCWSTR origin = (path + L"\\" + files.at(i)).wstring::c_str(); 
     LPCWSTR destination = (path + L"\\" + extensions.at(i) + L"\\" + files.at(i)).wstring::c_str(); 
     //move file 
     BOOL b = MoveFileW(origin, destination); 

MoveFileWはfalseを返します。
files.at(i)は、現在のファイルの名前であるwstringです。
extensions.at(i)は、の後に続くサブストリングです。 files.at(i)内にあります。たとえば、
files.at(0)mytext.txtの場合、extensions.at(0)txtです。 MoveFileWはfalseを返します。GetLastError()の場合、エラー123(ERROR_INVALID_NAME)が返されます。
ファイルを移動できないのはなぜですか?C++でMoveFileを使用してファイルを移動しようとするとERROR_INVALID_NAMEが返される

答えて

4

未定義の動作があります。 std::wstring::operator+が一時的な値を返していて、origindestinationが解放されたメモリを指しています。あなたがデバッガであなたのプログラムを見たなら、これを見たことはほぼ間違いありません。

にコードを変更し

wstring path = L"C:\\Users\\oneworduser\\Desktop\\trash"; 
wstring origin = path + L"\\" + files.at(i); 
wstring destination = path + L"\\" + extensions.at(i) + L"\\" + files.at(i); 
//move file 
BOOL b = MoveFileW(origin.c_str(), destination.c_str()); 
+0

ありがとうございます。これがなければこのプログラムは終了しませんでした。 – Carlos

0
LPCWSTR origin = (path + L"\\" + files.at(i)).wstring::c_str(); 

この行は '起源' にデータポインタを渡し、匿名wstringのオブジェクトを作成します。この行の後、匿名オブジェクトはデストラクタになり、 'origin'はすでに解放されているメモリを指します。

関連する問題