【问题标题】:Add a variable as pathname to CopyFile command in C++在 C++ 中将变量作为路径名添加到 CopyFile 命令
【发布时间】:2018-04-05 14:23:21
【问题描述】:

我一直在搜索,但似乎无法正确地将 CopyFile 命令中的路径替换为存储路径的变量。

这个想法是复制一个文件并用不同的数字重命名到某个目录。我设法让代码使用固定的路径名​​和文件名。但我需要复制这 1000 次,每次使用不同的数字。希望有人能告诉我如何将变量合并到 copyfile 命令中。

#include <iostream>
#include <fstream>
#include <windows.h>
#include <string>
#include <sstream>

using namespace std;
int main()
{


    int a=6;
    string name = "Slide";
    string newname;
    string directory = "d:/--- STEPHANE FILES ---/powerpoint/";
    string destination;

    ostringstream oss;
    oss << name << a ;
    newname = oss.str();


    ostringstream oss1;
    oss1 << directory << newname << ".JPG";
    destination = oss1.str();

    cout << destination;


    CopyFile("d:/--- STEPHANE FILES ---/powerpoint/Slide1.jpg", destination, TRUE);


    return 0;
}

【问题讨论】:

    标签: c++ file-copying pathname


    【解决方案1】:

    由于您使用的是 ANSI 版本,您可以将c._str() 成员函数传递给CopyFile

    CopyFile(directory.c_str(), destination.c_str(), TRUE);
    

    确保两个字符串都代表实际路径/文件名。

    【讨论】:

    • 我仍然收到我已经多次出现的错误:错误:无法将参数 '2' 的 'const wchar_t*' 转换为 'LPCSTR {aka const char*}' 到 'BOOL CopyFileA(LPCSTR , LPCSTR, BOOL)'|
    • @Stephane:您始终可以手动消除歧义:CopyFileA 明确采用 const char*CopyFileW 采用 const wchar_t*。请注意,如果您不控制文件名,则不能依赖CopyFileA。特别是,Documents and Settings 可能包含非 ASCII 用户名。
    猜你喜欢
    • 2012-04-10
    • 2019-11-22
    • 2021-02-28
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 2014-11-04
    • 2020-01-03
    相关资源
    最近更新 更多