write_c_string_literal.c 1014 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /*
  2. * Write data to a file or BinarySink in the form of a C string
  3. * literal, with any non-printable-ASCII character escaped
  4. * appropriately.
  5. */
  6. #include "defs.h"
  7. #include "misc.h"
  8. void BinarySink_put_c_string_literal(BinarySink *bs, ptrlen str)
  9. {
  10. for (const char *p = str.ptr; p < (const char *)str.ptr + str.len; p++) {
  11. char c = *p;
  12. if (c == '\n')
  13. put_datalit(bs, "\\n");
  14. else if (c == '\r')
  15. put_datalit(bs, "\\r");
  16. else if (c == '\t')
  17. put_datalit(bs, "\\t");
  18. else if (c == '\b')
  19. put_datalit(bs, "\\b");
  20. else if (c == '\\')
  21. put_datalit(bs, "\\\\");
  22. else if (c == '"')
  23. put_datalit(bs, "\\\"");
  24. else if (c >= 32 && c <= 126)
  25. put_byte(bs, c);
  26. else
  27. put_fmt(bs, "\\%03o", (unsigned)c & 0xFFU);
  28. }
  29. }
  30. void write_c_string_literal(FILE *fp, ptrlen str)
  31. {
  32. stdio_sink s;
  33. stdio_sink_init(&s, fp);
  34. put_c_string_literal(&s, str);
  35. }