Walker News

Build A C Program That Writes Output To File

Just realize that the system() function is not highly portable, so it is not ideal for writing info to file for debugging or logging purpose (like what I’ve done when debugging the DB2 external scalar function).

So, let’s use the fprintf() funtion to dump debugging info to error log file!

A sample program source code, writeErrlog.c, that appends data to app.errlog file in the C program working directory. The data logged into app.errlog includes the current timestamp and command-line option used during the program execution.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

const char *errFn = "app.errlog";
const char *fMode = "a";

int main(int argc, char **argv)
  char errTS[20];
  time_t errEpt;
  struct tm *errTm;
  FILE *errF = fopen(errFn, fMode);

  if (errF == NULL)
    printf("Cannot open %s!\n", errFn);

  errTm = localtime(&errEpt);
  strftime(errTS, 20, "%F %T", errTm);

  fprintf(errF, "%s input=%s\n", errTS, argv[1]);

  return 0;

Uses g++ to compile the binary program file:
g++ -o writeErrlog writeErrlog.c

To test it:
writeErrlog "hohoho"

And then you’ll find a new file named app.errlog in the same directory.

Custom Search

2016  •  Privacy Policy