Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fseek() on a pipe

Tags:

c

linux

I am trying to dynamically allocate memory for output of popen but trying to find the length of the file is giving "illegal seek" error. The code is

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
    char cmd[40] = {0};
    char * c;
    int byteCount = 0;
    FILE * pFp = NULL;
    strncpy(cmd, "ls -l", sizeof(cmd));
    pFp =  popen(cmd, "r");
    if (pFp == NULL)
        printf ("file is null");
    fseek(pFp, 0, SEEK_END);
    byteCount = ftell(pFp);
    perror("seek ");
    fclose(pFp);
}

fgets works fine, are there any constraints in using fseek with popen? Thanks in advance.

like image 960
user2212551 Avatar asked Dec 07 '22 05:12

user2212551


1 Answers

Yes you can't seek backwards from a pipe, only forwards. A pipe in the computer is just like a pipe in real life, the data flows only in one direction, and you can't change the flow.

like image 90
Some programmer dude Avatar answered Dec 14 '22 08:12

Some programmer dude