mahdi mohamadzade
mahdi mohamadzade

Reputation: 23

How to save a text file without format string in C

I want to save text into a file with this function that:

 void wl (char* buff[],char lp[],char mt[])
 {
  FILE *fp;
  fp=fopen(lp, mt);

  fprintf(fp, buff);
  fclose (fp);
  }

If I run it via a simple input buffer like "abcd" .... "abcd" will save into the destination file.

However, if I include text that contains "%s %d ...." or other C format strings ... it will save the wrong data.

I would like to know how I can save a string like "ab%cd" into a file. I know that if I replace % with %%, it will save correctly but I can't write the correct replace code for %

Upvotes: 2

Views: 518

Answers (2)

Xavier Holt
Xavier Holt

Reputation: 14619

Check out fputs and fwrite - neither of them perform any substitution. The former is probably all you're looking for, and easier to use as well, but fwrite gives you a little more power if you need it (it's typically used to write arbitrary binary to a file).

Hope that helps!

PS: Or, for a really lame, hackish solution, try:

fprintf(fp, "%s", buff); //Yuck!

Upvotes: 0

zch
zch

Reputation: 15278

You could do fprintf(fp, "%s", buff) or use fputs(buff, fp) that does the same.

You should probably never use any input as a formatting string - this can lead to exploits.

Upvotes: 1

Related Questions