How To Capture GPS NMEA Output in C Program

This post is divided into two sections, first one talks about send shell output to C program and second section makes use of this to show how to redirect GPS NMEA output in C program.

How to Capture the Output of a Linux Shell Command in C

If you google about how to redirect your shell output in C program, you will find couple of answers. There are few ways like using  freopen (“/dev/tty“, “a”, stdout) and playing around with ‘stdout’ file descriptor.

Other common approach is using ‘system’ command. The ‘system’ command executes the command.

int system (const char* command);

 With ‘system‘ function returns an integer indicating success or failure, but not the actual output of the string or command. This is useful when you do not need to stream the command output to your program.

When you need to re-direct command output to your program then you will need to use ‘popen’

popen - pipe to/from shell

FILE *popen(const char *command, const char *type);int pclose(FILE *stream);
Typically usage is:

     FILE *fp;
     char *command;

     /* command contains the command string (a character array) */

     /* If you want to read output from command */
     fp = popen(command,"r"); 
          /* read output from command */
           fscanf(fp,....);   /* or other STDIO input functions */

     /* If you want to send input to command */
     fp = popen(command,"w"); 
          /* write to command */
           fprintf(fp,....);   /* or other STDIO output functions */

The program cannot both send input to the command and read its output. You pass the command as a string to ‘popen’ function.

How to Capture GPS NMEA Output in C Program

Here is sample program using ‘popen’ to do this. What it does is creates a result buffer, opens up a read-only stream, runs the command, and captures the output, stuffs it into the buffer, then returns it as a string.

#include <stdio.h>
#include <stdlib.h>

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

  FILE *fp;
  int status;
  char result[512];
  int i=0;
  /* Open the command for reading. */
  fp = popen("gpspipe -r -x 5 | grep '$GPGGA'", "r");
  if (fp == NULL) {
    printf("Failed to run command\n" );
  /* Read the output a line at a time - output it. */
  if (fgets(result, sizeof(result), fp) != NULL) {
    printf("%s", result);

  else printf("no output \n");
  /* close */

  return 0;

This program uses ‘gpsd’ client programs to redirect NMEA output to command line. For more on how to install and test with ‘gpsd’ refer this post.

You should test the output of command first on command line. As you know making work GPS module is tricky.

Number of View :87

Tags: ,

  1. No comments yet.

Content Protected Using Blog Protector By: PcDrome.