【问题标题】:Set the absolute path with a variable on Linux using libcurl in C++在 C++ 中使用 libcurl 在 Linux 上使用变量设置绝对路径
【发布时间】:2014-11-14 03:23:17
【问题描述】:

如何在 Linux 上的 libcurl 中使用变量设置绝对路径?

这是一个示例代码:

   }
    string absolute_path = "/home/user_name";
    CURL *curl;
    FILE *fp;
    CURLcode res;
    const char *url = "http://google.com";
    const char outfilename[FILENAME_MAX] = absolute_path;
    curl = curl_easy_init();
    if (curl)
    {
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);
    }

但是编译器返回这个错误:

error: array must be initialized with a brace-enclosed initializer

有人知道怎么解决吗?感谢您的关注!

【问题讨论】:

  • const char outfilename[FILENAME_MAX] = absolute_path; 这行肯定是不正确的。实际上,您不需要 outfilename 变量。在fopen()中使用absolute_path.c_str()
  • 感谢您的帮助!
  • 解决了你的问题吗?
  • 我已经通过 user3159253 的回复解决了我的问题。

标签: c++ linux libcurl


【解决方案1】:

使用std::string类型的c_str()method

例如

const char* outfilename= absolute_path.c_str();

附:你有客观的理由来声明 const char 数组吗?

【讨论】:

  • 感谢您的回复,但我已经尝试过了,但编译器返回相同的错误。现在,我直接使用 user3159253 告诉我的 fopen() 方法,它可以工作。 P.S:我犯了一个错误,我已经将变量声明为 const char 数组,因为我正在经历(例如。我必须将 const char *url 声明为 const char 才能使用变量!
  • 像std::string path = "myValue"; const char* src = path.c_str(); 这样的简单示例永远不会失败。显然你有另一个问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多