我正在基于示例程序在 RHEL 4 Linux 上用 C 语言创建 SMTP 客户端程序:
http://curl.haxx.se/libcurl/c/simplesmtp.html
每当我通过标准输入将消息正文文本传递给程序时,程序都能正常运行。但是,当我尝试将 FILE 指针传递给 curl_easy_setopt() 函数时遇到段错误。注释(来自示例程序 simplesmtp.c)声明可以将文件指针而不是标准输入传递给 curl_easy_setopt 函数。
相关评论部分来自simplesmtp.c
/* You provide the payload (headers and the body of the message) as the
* "data" element. There are two choices, either:
* - provide a callback function and specify the function name using the
* CURLOPT_READFUNCTION option; or
* - just provide a FILE pointer that can be used to read the data from.
* The easiest case is just to read from standard input, (which is available
* as a FILE pointer) as shown here.
*/
curl_easy_setopt(curl, CURLOPT_READDATA, stdin);
这些是来自设置了 CURLOPT_VERBOSE 选项的控制台的错误行。
< 250 2.1.5 <myname@mydomain.com>... Recipient ok
> DATA
< 354 Enter mail, end with "." on a line by itself
./r: line 5: 21282 Segmentation fault ./mysmtpcli -r rcp.txt -m msg.txt
顺便说一句:./r 是我的 shell 脚本,它正在调用 ./mysmtpcli -r rcp.txt -m msg.txt
我的代码片段
FILE *f_msg;
f_msg = fopen(msg_file, "r");
if(!f_msg){
fprintf(stderr, "Could not load message file: %s\n", msg_file);
return 1;
}
curl_easy_setopt(curl, CURLOPT_READDATA, f_msg);
fclose(f_msg);
注意:msg_file 变量是从命令行参数填充的,是一个有效的文本文件,包含:
Subject: Test Message
This is a test message!
当使用“cat msg.txt | ./mysmtpcli -r rcp.txt”通过标准输入将同一文件传递给程序时,程序会正确执行。不过,这需要用标准输入替换 f_msg。
curl_easy_setopt(curl, CURLOPT_READDATA, f_msg);
我是否正确传递了 FILE 指针?
最佳答案
是的,你确实传递了一个文件指针。尽管您似乎立即将其关闭。如果这样做,curl 稍后将尝试从该文件中读取并崩溃。仅当不再需要时才需要关闭它。
关于c - 将 C FILE 指针传递给 curl_easy_setopt 函数的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12965650/