1

How can i download a file from a webserver, and save it in a specific path on Linux?

I have used this code (this is an expample):

CURL *curl;
FILE *fp;
CURLcode res;
const char *url = "http://google.com";
char outfilename[FILENAME_MAX] = "\\home\\user_name\\";
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);
}

But it doesn't work perfectly, because it save the file with the absolute path in his name only in the working directory!

Can anyone help me with this problem? Thank you for your attention!

Maury
  • 13
  • 2

1 Answers1

0

you need to use a forward slash, I suppose

char outfilename[FILENAME_MAX] = "/home/user_name/";
Sebastian
  • 1,408
  • 1
  • 20
  • 28
  • Thanks! It works! But how can i save the file in the main directory, "/"? (Example: /text.txt) – Maury Sep 19 '14 at 13:02
  • usually, one doesn't write to the root node `/`, because this requires `root` permissions. i.e. you need to run the command as `root` user. (e.g. `sudo ./a.out`) – Sebastian Sep 19 '14 at 13:04
  • Thanks again! Last question: How can i use a variable to specify the absolute path? It say me an error: Array must be initialized with a brace-enclosed initializer! – Maury Sep 19 '14 at 13:07
  • the error is a c++ compiler error see http://stackoverflow.com/a/4329352/543411. it seems unrelated to the original question. You can always open a new question specifically to this problem. To put it shortly: *Unfortunately I do not know.* ;-) – Sebastian Sep 19 '14 at 13:10
  • my pleasure. If this question is closed, you can upvote or accept my answer. cheers – Sebastian Sep 19 '14 at 13:16
  • Sorry, i can't upvote it, it says "Vote Up requires 15 reputation". But i have accepted it :) – Maury Sep 19 '14 at 13:23