C语言编写一个函数文件上传代码
时间: 2024-11-03 14:16:16 浏览: 23
在C语言中,由于它本身并不直接支持HTTP请求或文件上传功能,我们通常需要借助一些外部库,如`libcurl`(一个强大的URL传输工具库)来实现文件上传。以下是一个简单的示例,展示了如何使用`libcurl`发送POST请求并上传文件:
```c
#include <stdio.h>
#include <curl/curl.h>
// 文件上传函数
size_t write_callback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
FILE *fp = (FILE *)userp;
if (fp == NULL) {
return realsize;
}
// 将数据追加到文件
return fwrite(contents, size, nmemb, fp);
}
void upload_file(const char* filename, const char* url) {
CURL *curl;
CURLcode res;
FILE *file_to_upload = fopen(filename, "rb");
if (file_to_upload == NULL) {
fprintf(stderr, "Failed to open file.\n");
return;
}
curl_global_init(CURL_GLOBAL_DEFAULT); // 初始化CURL
curl = curl_easy_init(); // 创建CURL会话
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
// 设置文件指针作为回调,将数据逐块上传
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, file_to_upload);
res = curl_easy_perform(curl); // 执行上传操作
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
} else {
printf("File uploaded successfully!\n");
}
curl_easy_cleanup(curl); // 清理CURL会话
}
fclose(file_to_upload); // 关闭文件
curl_global_cleanup(); // 清理全局资源
}
// 示例用法
int main() {
const char* filename = "path_to_your_file.txt";
const char* server_url = "http://example.com/upload";
upload_file(filename, server_url);
return 0;
}
阅读全文