我有以下代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
int lendata;
printf("Content-type:text/html\n\n");
printf("<html><body>");
lendata = atoi(getenv("CONTENT_LENGTH"));
char *buf = malloc(lendata+1);
fread(buf,lendata,1,stdin);
printf("%s\n<br>",buf);
printf("%d",lendata);
free(buf);
printf("</body></html>");
return 0;
}
当我使用fgets
,它会截断显示的数据。但是当我使用fread
,它显示所有内容。顺便说一句,这是使用 post 方法上传 html 文件的 CGI 脚本。任何帮助将不胜感激。
这两个函数都有详细的文档记录(fread http://www.cplusplus.com/reference/cstdio/fread/, fgets http://www.cplusplus.com/reference/cstdio/fgets/)在 C++ 网站上。请参阅它们以了解深度和技术差异。
简而言之,fgets
将读取直到第一个新行,一次读取的最大字节数,或者EOF
,以先发送者为准,而fread
将读取特定数量的words(其中我将一个单词定义为一个字节块,例如 4 个字节的组)并在达到该限制或已读取 0 个字节时停止(通常意味着EOF
或错误)。
如果您想使用任一函数来读取直到EOF
那么它看起来如下:
char buffer[ buff_len ];
// ... zero-fill buffer here.
while ( fgets( buffer, buff_len, stdin ) != EOF ) {
// ... do something with buffer (will be NULL terminated).
}
while ( fread( buffer, sizeof( buffer[ 0 ] ), sizeof( buffer ) / sizeof( buffer[ 0 ] ), stdin ) != 0 ) {
// ... do something with buffer (not necessarily NULL terminated).
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)