Write to file and console in C

I am trying to write a function that allows me to write to the console and file in C.

I have the following code, but I realized that it doesn't allow adding arguments (e.g. printf).

#include <stdio.h> int footprint (FILE *outfile, char inarray[]) { printf("%s", inarray[]); fprintf(outfile, "%s", inarray[]); } int main (int argc, char *argv[]) { FILE *outfile; char *mode = "a+"; char outputFilename[] = "/tmp/footprint.log"; outfile = fopen(outputFilename, mode); char bigfoot[] = "It Smells!\n"; int howbad = 10; footprint(outfile, "\n--------\n"); /* then i realized that i can't send the arguments to fn:footprints */ footprint(outfile, "%s %i",bigfoot, howbad); /* error here! I can't send bigfoot and howbad*/ return 0; } 

I'm stuck here. Any tips? For the arguments I want to send the function: footprints, it will consist of strings, characters, and integers.

Are there any other printf or fprintf fns that I can try to create a wrapper?

Thanks and hope to hear your answers.

+4
source share
4 answers

You can use the <stdarg.h> vprintf both vprintf and vfprintf . For instance.

 void footprint (FILE * restrict outfile, const char * restrict format, ...) { va_list ap1, ap2; va_start(ap1, format); va_copy(ap2, ap1); vprintf(format, ap1); vfprintf(outfile, format, ap2); va_end(ap2); va_end(ap1); } 
+5
source

Printf, scanf, etc. functions use a variable length argument. Here is a tutorial on how you can create your own function to accept variable-length arguments.

0
source

Yes, there are several versions of printf . You are probably looking for vfprintf :

 int vfprintf(FILE *stream, const char *format, va_list ap); 

Functions of type printf should be variational functions (i.e., take a dynamic number of parameters).


Here is an example:

 int print( FILE *outfile, char *format, ... ) { va_list args; va_start (args, format); printf( outfil, format, args ); va_end (args); } 

Note that this only takes single parameters like printf: you cannot directly print an array with an integer.

0
source

Can you pass a char point that points to your string?

eg. (syntax not checked, but to give you an idea)

  #include <stdio.h> int footprint (FILE *outfile, char * inarray) { printf("%s", inarray); fprintf(outfile, "%s", inarray); } int main (int argc, char *argv[]) { FILE *outfile; char *mode = "a+"; char outputFilename[] = "/tmp/footprint.log"; outfile = fopen(outputFilename, mode); char bigfoot[] = "It Smells!\n"; int howbad = 10; //footprint(outfile, "\n--------\n"); char newString[255]; sprintf(newString,"%s %i",bigfoot, howbad); footprint(outfile, newString); return 0; } 
-1
source

Source: https://habr.com/ru/post/1334324/


All Articles