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.