用linux做文件上传的代码
时间: 2024-06-07 11:11:47 浏览: 7
下面是一个简单的Linux下使用cURL库进行文件上传的代码示例:
```c
#include <stdio.h>
#include <curl/curl.h>
int main(int argc, char *argv[])
{
CURL *curl;
CURLcode res;
FILE *fp;
char *url = "http://example.com/upload.php";
char *filename = "/path/to/file";
/* 以二进制方式打开要上传的文件 */
fp = fopen(filename, "rb");
if (!fp) {
printf("Failed to open file: %s\n", filename);
return 1;
}
/* 初始化curl */
curl = curl_easy_init();
if (curl) {
/* 设置上传的URL */
curl_easy_setopt(curl, CURLOPT_URL, url);
/* 设置要上传的文件 */
curl_easy_setopt(curl, CURLOPT_READDATA, fp);
/* 开启POST上传 */
curl_easy_setopt(curl, CURLOPT_POST, 1L);
/* 执行上传操作 */
res = curl_easy_perform(curl);
/* 检查上传是否成功 */
if (res != CURLE_OK) {
printf("Failed to upload file: %s\n", curl_easy_strerror(res));
}
/* 关闭curl */
curl_easy_cleanup(curl);
}
/* 关闭文件 */
fclose(fp);
return 0;
}
```
需要注意的是,要上传的文件的路径和上传的URL需要根据实际情况进行修改。此外,还需要安装cURL库,可以使用以下命令在Ubuntu下进行安装:
```
sudo apt-get install libcurl4-openssl-dev
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)