1

I'm trying to download a test file from my server using the cURL library with this code:

#define CURL_STATICLIB

#include <stdio.h>
#include <curl/curl.h>
#include <curl/types.h>
#include <curl/easy.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;

    char *url = "http://pixhost.tk/test.txt";
    char outfilename[FILENAME_MAX] = "/Users/Nathan/Desktop";
    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);

        res = curl_easy_perform(curl);

        curl_easy_cleanup(curl);
        fclose(fp);
    }

    return 0;
}

And compiling it like this:

$ gcc main.c -lcurl -o curltest

But when I execute it I'm getting a Segmentation Fault error. What should I do to correct this?

2 Answers 2

3

I'm not familiar with cURL, but two things that might help you, so forgive me if I speak nonsense:

  1. char *url = "http://pixhost.tk/test.txt"; is a read-only string, so change it to const char *url = "http://pixhost.tk/test.txt"; this might reveal your problem during compilation.
  2. You don't check for the result of fopen, maybe it failed, which explains the segfault, and it is seems likely to me since you try to open "/Users/Nathan/Desktop" which should be a directory AFAIK.
Sign up to request clarification or add additional context in comments.

1 Comment

Me too, a3_nm. It looks like he is trying to open a directory for write.
0

It's been a while since I worked with curl, and I'm not sure this would cause a segfault, I think you should be calling fwrite like this:

fwrite(ptr, 1, nmemb * size, stream);

Because fwrite returns the number of elements written, and size is not (I don't think) guaranteed to be one. And since you're returning what fwrite returns, I believe you're returning less bytes than you're actually writing, since the function is supposed to return how many bytes it wrote.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.