Home > Mobile >  How to write the string representation of the contents of a file?
How to write the string representation of the contents of a file?

Time:04-15

In my file let's assume it has the following content:

my_file.txt

/* My file "\n". */
Hello World

If I wanted generate a file and pass this same content as a string in C code, the new file would look like this:

my_generated_c_file.c

const char my_file_as_string[] = "/* My file \"\\n\". */\nHello World\n\n";

In an unfortunate attempt, I tried to simply add the chars one by one:

#include <stdio.h>
int main ()
{
  FILE *fp_in = fopen("my_file.txt", "r");
  FILE *fp_out = fopen("my_generated_c_file.c", "w");

  fseek(fp_in, 0L, SEEK_END);
  long size = ftell(fp_in);
  fseek(fp_in, 0L, SEEK_SET);

  fprintf(fp_out, "const char my_file_as_string[] = \"");
  while (size--) {
    fprintf(fp_out, "%c", getc(fp_in));
  }
  fprintf(fp_out, \";\n\n");

  fclose(fp_in);
  fclose(fp_out);
  return 0;
}

But that doesn't work because a '\n' for example is read as a line break and not "\\n".

How to solve this?

CodePudding user response:

You could simply print a '\\' wherever a '\' was present in the original file:

while (size--) {
    char next_c = getc(fp_in);
    if(next_c == '\') {
      fprintf(fp_out, "\\\\");
    }
    else {
      fprintf(fp_out, "%c", next_c);
    }
  }

You'll probably also want to perform other such transformations as well, such as replacing line breaks with \n.

  • Related