Path: utzoo!attcan!uunet!lll-winken!csd4.milw.wisc.edu!mailrus!tut.cis.ohio-state.edu!bloom-beacon!oberon!nunki.usc.edu!jeenglis From: jeenglis@nunki.usc.edu (Joe English) Newsgroups: comp.lang.c Subject: Re: Want a way to strip comments from a Message-ID: <3114@nunki.usc.edu> Date: 19 Mar 89 02:48:32 GMT References: <7150@siemens.UUCP> <9900010@bradley> <4896@cbnews.ATT.COM> <978@philmds.UUCP> Reply-To: jeenglis@nunki.usc.edu (Joe English) Organization: N of A Lines: 68 leo@philmds.UUCP (Leo de Wit) writes: >In article <4896@cbnews.ATT.COM> smk@cbnews.ATT.COM (Stephen M. Kennedy) writes: >|In article <9900010@bradley> brian@bradley.UUCP writes: >|> The following works in vi: :%s/\/\*.*\*\///g >| >|/* And this */ important_variable = 42 /* doesn't work either! */ > >And how about: > > puts(" A comment /* in here */"); > >And you can give more examples showing it isn't that trivial; a challenge >for the sed adept, perhaps ... Does it *have* to be done in sed/awk/other text processor? This problem is fairly difficult to solve using regexp/editor commands, but it's a piece of cake to do in C: #include void eatcomment(void); main() { int ch; int instring = 0; ch = getchar(); while (ch != EOF) { switch (ch) { case '"' : instring = !instring; break; case '/' : if (!instring) if ((ch = getchar()) == '*') { eatcomment(); ch=getchar(); } else putchar('/'); break; case '\\' : /* in case this is a \" in a string, */ putchar('\\'); /* pass it through now and don't let */ ch = getchar(); /* the switch() eat it */ } putchar(ch); ch = getchar(); } exit(0); } void eatcomment(void) { int ch; for (;;) { ch = getchar(); while (ch == '*') if ((ch = getchar()) == '/') return; if (ch == EOF) exit(1); /* oops */ } } ------------ This hasn't been tested thoroughly; it's mostly from memory. Joe English jeenglis@nunki.usc.edu