【发布时间】:2011-05-12 08:14:57
【问题描述】:
我想确定 popen() 函数调用返回的流大小。我尝试使用 fseek 和 ftell,但它返回的大小为 -1。谁能建议我如何确定文件大小?以下是我正在使用的代码......
char return_val[256];
FILE *fp = NULL;
char line[256];
memset (return_val, 0, 256);
/* set the defalut value */
strncpy (return_val, "N/A", 4);
char cmd[] = "if [ -f /etc/version ]; then cut -d, -f1 -s /etc/version ; fi";
/* Open the command for reading. */
fp = popen(cmd, "r");
if (fp != NULL)
{
/* read the line from file */
fgets (line, 256, fp);
if( line != NULL)
{
/* copy the data */
strncpy(return_val, line, strnlen (line, 256));
}
/* close the file */
pclose (fp);
}
【问题讨论】:
-
第一:使用 ftell/fseek 来确定文件的大小是一个大杂烩。请改用特定于平台的机制,例如 stat(2)。其次, ftell 不会“将大小返回为 -1”。它返回 -1 表示发生了错误。也就是说,您试图在一个非常规文件上调用 ftell。
-
@William:感谢您的回复。我想我不能在这里使用 stat() 因为 popen() 只返回指向流的指针。 stat() 需要命名文件来检查属性。是的, ftell() 返回 -1(错误),因为我试图访问不是常规文件的 popen() 流。是否有任何工作可以确定 poopen() 流大小?
-
“流大小”是什么意思?一条河里有多少水?您可以在底层文件描述符上使用 fstat,但如果您想获取大小,这样做是没有意义的,因为大小的概念对管道没有意义。
-
@William:感谢您的回复。我已经明白你所说的了。感谢您的 cmets。