简体   繁体   中英

redirecting shell command output to C program

I have the following program :

/* a.c */ 
#include <stdio.h>

int   
main(int argc, char* argv[]){     

size_t size=0;    
char* lineptr;      

    while(getline(&lineptr, &size, stdin)){           
        fprintf(stderr, "line = %s\n", lineptr);      
        if(lineptr){      
            free(lineptr);     
            lineptr = NULL;     
        }      
    }      

return 0;      
}      

I redirected the output of shell command "ls" to this program using the
following line :

ls | ./a.out

Expected output :
program should print the name of all files in the current directory
and terminate.

Actual output :
The program prints the name of all the files but does not terminate,
instead it loops infinitely and prints the last entry infinitely.

Thanks

GNU's getline function returns -1 upon end-of-file (or error). Use

while(-1 != getline(&lineptr, &size, stdin))

...and set lineptr to NULL before the first call to getline .

Also, you don't have to free the pointer in every iteration of the loop; you can reuse the previous pointer and free once at the end:

size_t size = 0;
char* lineptr = NULL;

while(-1 != getline(&lineptr, &size, stdin)){
  fprintf(stderr, "line = %s", lineptr);
}

free(lineptr);

getline will use realloc internally as needed. Note that you have to make sure that lineptr and size are not changed between calls to getline for this to work (although you may change the string to which lineptr points).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM