我的代码遇到了一些问题。编译程序后出现分段代码错误。我想构建简单的下载工具,所以我使用最简单的想法。(用户将 url 和程序下载文件输入用户桌面)。您能否给我一些提示,如何使该程序工作或如何将其转换为更好的程序(要求更高的代码,结果更好)。
#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] - pdfn [1] - jpgn [2] - txtn "); //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;
}
代码无法正常工作的原因有多种:
-
path_pdf
、path_jpg
和path_txt
应键入char*
-
FILEPATH
应该像RaptorDotCpp指出的那样char FILEPATH[3] = {path_pdf, path_jpg, path_txt};
宣布。 -
您的第二个
scanf
调用应该是scanf("%d", &x);
,因为 scanf 要求格式后面的参数是指针。这是我测试时您的代码段错误的地方。 -
url
应初始化为char *url = y;
。这会url
设置为用户输入的值,而不仅仅是字母"y"。 -
outfilename[FILENAME_MAX] = FILEPATH[x];
写过了outfilename
的结尾。请改用outfilename = FILEPATH[x];
,这不会导致缓冲区溢出。