【发布时间】:2016-02-16 11:30:57
【问题描述】:
我有一个基于 linux 的嵌入式系统,并使用 cURL 库从网络摄像机拍摄快照。
我的相机提供了一些 CGI 功能,其中之一是用于拍摄图像快照。
调用专用 CGI 功能后,相机成功发送拍摄的照片作为响应。
我将相机响应保存为 jpg 文件,到目前为止一切正常。
但是当网络连接中断时,我的代码会生成一个大小为零的 jpg 文件。
我删除了零大小的图像,但最好不要保存图像,以防 curl_easy_perform(curl) 调用返回错误。
如果 cURL 出错,是否可以禁用保存?
const int maxNumberOfImages = 20;
CURL *curl;
CURLcode result;
FILE *CURLOPT_WRITEFUNCTION_FILE;
bool flag = true;
string url = "http://admin:1234@";//needs refactory
url.append(ip);
url.append(":80/snapshot.jpg");
DEBUG_PRINT(url);
char actionDate[20];
time_t now = time(NULL);
strftime(actionDate, 20, "%Y-%m-%d %H:%M:%S", localtime(&now));
char *directory = "/root/rootfs_frequent_rw/snapshots/";
string fileName = directory;
fileName.append(cam_name);
fileName.append("___");
fileName.append(actionDate);
fileName.append(".jpg");
createDirectoryIfNotExist(directory);
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
CURLOPT_WRITEFUNCTION_FILE = fopen(fileName.c_str(), "wb");
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEDATA, CURLOPT_WRITEFUNCTION_FILE);
result = curl_easy_perform(curl);
if(result != CURLE_OK){
DEBUG_PRINT("ERROR\n");
flag = false;
}
else
DEBUG_PRINT("SUCCESS\n");
curl_easy_cleanup(curl);
}
fclose(CURLOPT_WRITEFUNCTION_FILE);
cx based embedded system and taking snapshots from an ip camera. url_global_cleanup();
isFileEmpty(fileName.c_str()); //if file is zero sized delete it.
if(flag)
return ReturnValue::return_success;
return ReturnValue::return_operation_failed;
【问题讨论】:
-
该文件已由
fopen()创建,此处为:CURLOPT_WRITEFUNCTION_FILE = fopen(fileName.c_str(), "wb");。所以问题超出了 CURL 库的范围。一种选择是将数据保存到内存缓冲区中,然后在看起来正常时将其保存到文件中。 -
使用一致的命名风格和适当的标识符大小写。虽然很少有普遍接受的一般规则,但像
CURLOPT_WRITEFUNCTION_FILE这样的全大写标识符预计只能是宏或枚举常量。而且C不是C++不是C。不要加无关的标签。