This page has been designed specifically for the printed screen. It may look different than the page you were viewing on the web.
Please recycle it when you're done reading.

The URI for this page is { http://cc.byexamples.com }

writing log files or config files uses fprintf Posted on January 23rd

To write formatted string to files, the easiest way is uses fprintf. It works exactly the same way like printf.


File * fp=fopen("filename","w");

fprintf(fp,"%s.%s = %d\n", szTag,szSubTag,nValue);

fclose(fp);

In case you want to create your own fprintf, can uses stdarg’s function - vfprintf


//Assume you have access to file pointer at outside
File * fp;
int WriteLog(char *str,...)
{
    //fp is null, file is not open.
    if (fp==NULL)
          return -1;

    fprintf(fp,"%d : ",time(NULL));
    va_list arglist;
    va_start(arglist,str);
    vfprintf(fp,str,arglist);
    va_end(arglist);
    fprintf(fp," \n");

    return 1;
}

I simply uses time() to returns me a time value in seconds since the Epoch, it is just a simple example of how you can use fprintf and also vfprint to write text based file such as logs and config files.

I have tried to put just “\n” in fprintf to leave a blank line but it fails, but with a blank space together with “\n”, it works!

For va_list usage, refers back to va_list examples.

Trackback URL

One Response to “writing log files or config files uses fprintf” :

  1. Shouldn’t the first line read “FILE” not File?

    Commented Bob on June 30th, 2007.
Leave your own comments about this post: