www.digitalmars.com         C & C++   DMDScript  

D - str2d.c: Utility that Converts D source file to a D string

reply Russ Lewis <spamhole-2001-07-16 deming-os.org> writes:
I found this mini-utility useful, and thought I would share it with the
community.  I would have written in D, but any time I referenced "stdin"
(for feof or fgets) I was getting compile errors, so it was quicker to
just port it to C than figure out what I did wrong.

I think this would be a useful function to implement for the D standard
library.

If anybody has any bugfixes, send 'em.



// the only purpose of this program is to read stdin, convert it
// to a D string that represents it, and output that to stdout.
// The output includes the quotes (single or double) around the
// string, but does not include any variable to save it nor
// any trailing semicolon.  You need to add those.
//
// So you might use this program like this:
//   {
//     echo "module file;"
//     echo "char[] file_str = \c"
//     str2d <file.txt
//     echo ";"
//   } >file.d

#include <stdio.h>

int main()
{
  putchar('\'');
  while(!feof(stdin))
  {
    char str[1024];
    int len;
    int s;

    fgets(str,sizeof(str),stdin);
    len = strlen(str);

    for(s=0; s<len; s++)
      switch(str[s])
      {
      case '\'':
        printf("' \\' '");
        break;

      case '\n':
        printf("' \\n\n'");
        break;

      case 0:
        printf("ERROR ERROR ERROR\n");
        return -1;

      default:
        putchar(str[s]);
      }
  }
  putchar('\'');

  return 0;
}

--
The Villagers are Online! http://villagersonline.com

.[ (the fox.(quick,brown)) jumped.over(the dog.lazy) ]
.[ (a version.of(English).(precise.more)) is(possible) ]
?[ you want.to(help(develop(it))) ]
Nov 05 2002
parent Burton Radons <loth users.sourceforge.net> writes:
Russ Lewis wrote:
 I found this mini-utility useful, and thought I would share it with the
 community.  I would have written in D, but any time I referenced "stdin"
 (for feof or fgets) I was getting compile errors, so it was quicker to
 just port it to C than figure out what I did wrong.
stdin/out/err are implemented using proprietary macros, so I need to put in a version for GNU C.
 I think this would be a useful function to implement for the D standard
 library.
Actually, fmt already has this using fmt ("%r", string). For example: println ("%r", "hello, world") -> 'hello, world' println ("%r", 'foo' \n 'bar') -> "foo\nbar"
Nov 05 2002