I want to wget in C and I am using popen to do so.
FILE *stdoutPtr = popen(command,"r");
fseek(stdoutPtr, 0L, SEEK_END);
long pos = ftell(stdoutPtr);
Here I want to get the size of stdout so that I can initialize buffer. But pos variable is always -1.
pos is supposed to tell me current position of read pointer.
Please help….
The
FILEreturned bypopenis not a regular file, but a thing called apipe. (That’s what thepstands for.) Data flows through the pipe from the stdout of the command you invoked to your program. Because it’s a communications channel and not a file on disk, a pipe does not have a definite size, and you cannot seek to different locations in the data stream. Therefore,fseekandftellwill both fail when applied to thisFILE, and that’s what a-1return value means. If you inspecterrnoimmediately after the call toftellyou will discover that it has the valueESPIPE, which means “You can’t do that to a pipe.”If you’re trying to read all of the output from the command into a single
char*buffer, the only way to do it is to repeatedly call one of the read functions until it indicates end-of-file, and enlarge the buffer as necessary usingrealloc. If the output is potentially large, it would be better to change your program to process the data in chunks, if there’s any way to do that.