Search code examples
cioformattingprintfstring-formatting

Read format specifiers from text file


Is there a way to read a format specifier, such as %s or %d from a text file and then use this specifier in a string variable for a printf later on?

For example, if I had a file that contains

foo=%s

would i be able to do something like this?

FILE * f = fopen("/home/foo/bar", "r");

charn * s_buf = malloc(sizeof(charn) * 256);
fgets(s_buf, 255, f);
  
printf(s_buf, "bar");

and get this printed as a result:

foo=bar

I know it obviously doesn't work exactly like this, but i hope you understand what I'm going for and maybe know of a way to do something like this


Solution

  • Your code is correct but you have to think about what will happen if the file contains a %d instead of a %s, or any other invalid format specifier for what has to be displayed.

    It is correct to malloc() space for s_buf but a static array will do as well. You won't need to call free(s_buf) later.