0

I'm having some problems with my code. I get segmentation code error after compiling my program. I want to build simply download tool so i'm using the simplest ideas for it.(User enters the url and program download file into users desktop). Could you give me some tips how to make this program work or how to convert it to better one (more demanding code with better results).

#define CURL_STATICLIB
#include <stdio.h>
#include <curl/curl.h>
#include <string.h>

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
    size_t written;
    written = fwrite(ptr, size, nmemb, stream);
    return written;
}

int main(void)
{
    CURL *curl;
    FILE *fp;
    CURLcode res;
    int x;
    char y[200];
    char page;
    char outfilename[FILENAME_MAX];
    char path_pdf = "/home/user_name/Desktop/document.pdf";
    char path_jpg = "/home/user_name/Desktop/picture.jpg";
    char path_txt = "/home/user_name/Desktop/document.txt";
    char FILEPATH[2] = {path_pdf, path_jpg, path_txt};
    printf("Enter file url \n"); // for example http://oi58.tinypic.com/15nk3de.jpg
    scanf ("%s",y);
    char *url = "y";
    printf("Choose type of file:\n [0] - pdf\n [1] - jpg\n [2] - txt\n "); //choose 1
    scanf("%d",x);
    outfilename[FILENAME_MAX] = FILEPATH[x];
    curl = curl_easy_init();
    if (curl)
    {
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        curl_easy_setopt (curl, CURLOPT_VERBOSE, 1L);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);
    }
    return 0;
}
davoid
  • 327
  • 2
  • 10
  • `char FILEPATH[2] = {path_pdf, path_jpg, path_txt};`. There's 3 elements in that array, not 2. Additionally, strings in C are of the type `char*`, not `char`. – RaptorDotCpp Dec 28 '14 at 15:01

1 Answers1

1

There are several reasons that your code isn't working:

  • path_pdf, path_jpg, and path_txt should be type char*

  • FILEPATH should be declared as char FILEPATH[3] = {path_pdf, path_jpg, path_txt}; as RaptorDotCpp pointed out.

  • Your second scanf call should be scanf("%d", &x); since scanf requires the arguments after the format to be pointers. This is where your code segfaulted when I tested it.

  • url should be initialized as char *url = y;. This sets url to the value the user entered instead of only the letter "y".

  • outfilename[FILENAME_MAX] = FILEPATH[x]; writes past the end of outfilename. Use outfilename = FILEPATH[x]; instead, which won't cause a buffer overflow.

Community
  • 1
  • 1
Quip Yowert
  • 444
  • 2
  • 7
  • Sorry for not not correcting this " basic one " mistakes before posting. Program compiles normally until the near end of its operation when the image should be downloaded into the desktop. I'm still getting segmentation fault [error](https://imgur.com/Y3ooOLC). – davoid Dec 28 '14 at 21:26