Question about fprintf, sprintf and their arguments

Hey guys. In my program I have created a log system that uses an argument to determine how much the function can print to my program log, so I can easily control the logs and make debugging easier...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
... 
// My Defines
#define SILENT 0 // no log output
#define QUIET 1 // minimal log output
#define NORMAL 2 // normal log output
#define LOUD 3 // extra info is printed to help with debugging
...
// An example function using the printSetting control variable
void myFunction(int printSetting){
if(printSetting >= QUIET) fprintf(log, "\n\myFunction called.");
...
// My main function that calls the example function above
int main(){
myFunction(NORMAL);
}


... I am however finding it annoying to print the following every time I need to output to the log...

 
if(printSetting >= QUIET) fprintf(log, "\n\myFunction called.");


... :) My idea is to extend the fprintf function to take an extra argument. E.g..

 
extended_fprintf(FILE *f, int printSetting, ... // etc 


... however fprintf and sprintf can both take numerous arguments, and I would like to know if this is due some cool feature of c++ that I am yet to learn about, or are there are just a ton of function prototypes for fprintf? :)

Thanks in advance!
The cool feature is known as variable arguments or varargs. Look at varargs.h.
Brilliant thank you :) I found some examples in my c++ reference book. I just didn't know what to search for to begin with!

You Legend.
This was suprisingly simple after Kooths kind nudge in the right direction. So here is a simple solution incase anyone finds this and wants to accomplish something similar...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
...
#define SILENT 0
#define QUIET 1
#define NORMAL 2
#define LOUD 3
..
// vfprintf needs to be used instead of fprintf so that you can pass the va_list to it instead of worrying about the specific arguments
int toLog(FILE *f, int functionPrintSetting, int currentPrintSetting, const char *buffer, ...){
	if(currentPrintSetting >= functionPrintSetting){
		va_list arguments;
		va_start(arguments, buffer);
		int r = vfprintf(f, buffer, arguments);
		va_end(arguments);
		return r;
	}else{
		return 1;
	}
}
...
void myFunction(int printSetting){

	int value1 = 6;
	toLog (file, printSetting, QUIET, "\n\nSome log text I only want to print if the current mode is QUIET or higher - %u", value1);

	int value2 = 23;
	toLog(file, printSetting, LOUD, "\n\nSome text I only want to print if the current mode is LOUD or higher - %u", value2);

}
...
int main(){
	// Now I call myFunction() in four different ways so it prints to my log in any amount of detail that I want :)
	myFunction(LOUD);
	myFunction(NORMAL);
	myFunction(QUIET);
	myFunction(SILENT);
}

Last edited on
Topic archived. No new replies allowed.