2014-09-19 44 views
0

如何在Linux上使用變量設置libcurl中的絕對路徑?在Linux上使用libcurl在C++中使用變量設置絕對路徑

下面是一個例子代碼:

} 
    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 

有誰知道如何解決它?感謝您的關注!

+1

行'const char outfilename [FILENAME_MAX] = absolute_path;'肯定是不正確的。其實,你不需要'outfilename'變量。在'fopen()'中使用'absolute_path.c_str()'' – user3159253 2014-09-19 13:51:51

+0

請參閱http://stackoverflow.com/questions/4329324/c-error-array-must-be-initialized-with-a-brace-enclosed-initializer – iqstatic 2014-09-19 13:57:21

+0

感謝您的幫助! – QuestionMan 2014-09-19 14:04:14

回答

1

使用c_str()methodstd::string的類型

例如

const char* outfilename= absolute_path.c_str();

P.S.你有一個客觀的理由來聲明const char數組嗎?

+0

感謝您的答覆,但我已經嘗試過,但編譯器返回相同的錯誤。現在,我直接使用方法fopen()作爲user3159253告訴我,它的工作原理。 PS:我犯了一個錯誤,我已經將變量聲明爲const char數組,因爲我正在體驗(例如,我必須將const char * url聲明爲使用變量的const char! – QuestionMan 2014-09-19 14:02:51

+0

一個簡單的示例,例如'std :: string path =「myValue」; const char * src = path.c_str();''不應該失敗。顯然你有另一個問題 – deimus 2014-09-19 14:11:07