2

Basically what I wan to do is "redirect" printf message to a log file. So I created this function for this:

the header file is

#ifndef LOGGER_H
#define LOGGER_H

/* 
 * Simple interface to a logger application to simplify the use of writting the output to a file on disk
 */

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

#define  LOG_OUTPUT  "log.txt"

void logOut(const char *control_string, ...);

#endif // LOGGER_H

And the .c file is

#include "logger.h"

#define  LOG_OUTPUT  "log.txt"

void logOut(const char *control_string, ...){
   FILE *fp;
   fp = fopen(LOG_OUTPUT,"ab+");

   va_list argptr;
   va_start(argptr,control_string);
   fprintf(fp,control_string,argptr);
   va_end(argptr);
   fclose(fp);
}

Here is me trying it out

int main()
{
   logOut("Hello World\n");
   printf("Printing the same value in decimal an hex: %3d\n",215);
   logOut("Printing the same value in decimal an hex: %3d\n",215);

   printf("\nDone\n"); 
   return 0;
}

And here is the output I get:

Printing the same value in decimal an hex: 215

Done

Checking out the log.txt file contents:

Hello World
Printing the same value in decimal an hex: 482410768

So my question is, what am I doing wrong?

aarelovich
  • 5,140
  • 11
  • 55
  • 106
  • 7
    In `logOut`, you should call `vfprintf`, but you call plain old `fprintf`. – M Oehm Apr 01 '20 at 11:18
  • 1
    `vfprintf` function works with `va_list` instead of variable number of arguments. Therefore you should use `vfprintf` instead of `fprintf`. – aep Apr 01 '20 at 11:23
  • Thank you @MOehm! This was the problem! Put it as answer if you want so you can get the credit! – aarelovich Apr 01 '20 at 11:36

0 Answers0