Page 161 - C-Language
P. 161
void print_all(FILE *stream)
{
int c;
while ((c = getc(stream)) != EOF)
putchar(c);
}
int main(void)
{
FILE *stream;
/* call netstat command. netstat is available for Windows and Linux */
if ((stream = popen("netstat", "r")) == NULL)
return 1;
print_all(stream);
pclose(stream);
return 0;
}
This program runs a process (netstat) via popen() and reads all the standard output from the
process and echoes that to standard output.
Note: popen() does not exist in the standard C library, but it is rather a part of POSIX C)
Get lines from a file using getline()
The POSIX C library defines the getline() function. This function allocates a buffer to hold the line
contents and returns the new line, the number of characters in the line, and the size of the buffer.
Example program that gets each line from example.txt:
#include <stdlib.h>
#include <stdio.h>
#define FILENAME "example.txt"
int main(void)
{
/* Open the file for reading */
char *line_buf = NULL;
size_t line_buf_size = 0;
int line_count = 0;
ssize_t line_size;
FILE *fp = fopen(FILENAME, "r");
if (!fp)
{
fprintf(stderr, "Error opening file '%s'\n", FILENAME);
return EXIT_FAILURE;
}
/* Get the first line of the file. */
line_size = getline(&line_buf, &line_buf_size, fp);
/* Loop through until we are done with the file. */
while (line_size >= 0)
https://riptutorial.com/ 137

