本來這個blog是記錄開發輸入法的點滴的,後來越來越雜,現在什麼都記錄了。

2011年2月9日 星期三

C++ program to remove C/C++ style comments, while keep string content intact and line numbers of code unchnaged...

#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string>
#include <iostream>
#include <vector>
#include <string>

int my_fgets(std::string &str, FILE *fp, unsigned char to_remove_comments) {
    // read one line from file. if end of file return 0 otherwise return 1
    int ret=1;
    static unsigned char prev_linebreak;
    unsigned char ch;

    str.clear();

    while(1) {
        ch = fgetc(fp);

        if (feof(fp)) {
            prev_linebreak='\0';
            if (str.empty())
                ret=0;
            break;
        }

        if (ch=='\r') {
            prev_linebreak='\r';
            break;
        }

        if (ch=='\n') {
            if (prev_linebreak=='\r') {
                prev_linebreak='\0';
                continue;
            } else {
                prev_linebreak='\n';
                break;
            }
        }
        str+=ch;
    }

    if (to_remove_comments)
    {
        std::string tmpstr=str;
        
        static enum IN_COMMENT_T {
            IN_COMMENT_NOT,
            IN_COMMENT_WAIT_FOR_STAR_SLASH,
            IN_COMMENT_DOUBLE_QUOTE,
        } in_comment = IN_COMMENT_NOT;
        const char *p, *p_limit, *p_start;
        
        str.clear();
        p_start = tmpstr.c_str();
        p_limit = p_start + tmpstr.length();
        
        for(p=p_start; p<p_limit; p++) {
            switch(in_comment) {
            case IN_COMMENT_NOT:
                if (strncmp(p, "//", 2)==0) {
                    p=p_limit-1;
                    continue;
                } else if (strncmp(p, "/*", 2)==0) {
                    in_comment=IN_COMMENT_WAIT_FOR_STAR_SLASH;
                    p+=(sizeof("/*")-1)-1;
                } else if (*p=='"') {
                    // avoid case like '"'
                    if (p==p_start || *(p-1)!='\'')
                        in_comment=IN_COMMENT_DOUBLE_QUOTE;
                }
                break;
            case IN_COMMENT_WAIT_FOR_STAR_SLASH:
                if (strncmp(p, "*/", 2)==0) {
                    in_comment=IN_COMMENT_NOT;
                    p+=sizeof("*/")-1;
                }
                break;
            case IN_COMMENT_DOUBLE_QUOTE:
                if (*p=='"') {
                    // need to count how many '\' in the front. If it is even number then end of quote!
                    const char *q;
                    for(q=p-1; q>=p_start && *q=='\\'; q--);
                    if ((p-q)&1) {
                        // note (p-q)-1 is the number of '\\' before '"'.
                        // if ((p-q)-1) is odd, the " is escaped.
                        // if ((p-q)-1) is even, the " is a real close quotoation.
                        in_comment=IN_COMMENT_NOT;
                    }
                }
                break;
            default:
                break;
            }
        
            if (in_comment==IN_COMMENT_NOT || in_comment==IN_COMMENT_DOUBLE_QUOTE)
                str = str+*p;
        }
        
        if (ret==0)
            in_comment = IN_COMMENT_NOT;
    }

    return ret;
}

int 
main(int argc, char **argv) {
    FILE *fp=NULL;
    std::string str;

    if (argc!=2) {
        fprintf(stderr, "remove C style comment in a text file and show in stdout\n");
        fprintf(stderr, "usage: %s file\n", argv[0]);
        goto MAIN_ERROR;
    }

    fp=fopen(argv[1], "rb");

    if (fp==NULL)  {
        fprintf(stderr, "error in open %s\n", argv[1]);
        goto MAIN_ERROR;
    }

    while(my_fgets(str, fp, 1))
        fprintf(stderr, "%s\n", str.c_str());

                    
MAIN_ERROR:
    if (fp)
        fclose(fp);

    return 0;

}

22 則留言:

匿名 提到...

order carisoprodol online carisoprodol 350 wiki - carisoprodol no prescription needed

匿名 提到...

ï»?You can show your support to your NHL team or NFL team by wearing the NFL jerseys and NHL jerseys You however have to keep in mind that the items that are available in such sites will be second hand ones
ï»?This type of Frames per second is simply extraordinary! I have to announce magnificent as with any Call of Duty The jerseys are now made available for online purchase at very low prices

匿名 提到...

8Y2n2c6n9f vigrx plus montreal , [URL=http://vigrxplusindonesia.id.st/]read more[/URL] 1n1d4g4j8p

匿名 提到...

3a5r8v3w4q total stranger , [URL=http://buyvigrxplussouthafrica.lo.gs/]read full article[/URL] 3n7o8n1g2j

匿名 提到...

4p5b1i1z6w imp source , [URL=http://vigrxplusuk.lo.gs/]sneak a peek at this web-site.[/URL] 8m8n0j5a5t

匿名 提到...

3v5q7q7g2u helpful resources , [URL=http://vigrxpluscanada.lo.gs/]go to my blog[/URL] 2e4w8s9a2X

匿名 提到...

9g6n5w6p8e vigrx plus jelqing , [URL=http://vigrxplusaustralia.lo.gs/]address[/URL] 1a2g9m4e3h

匿名 提到...

6o5j8o1e2c check my source , [URL=http://vigrxplusindia.ek.la/]talks about it[/URL] 6g6f6f4t9h

匿名 提到...

7a9u7s0q9n vigrx plus exercises , [URL=http://buyvigrxplusphilippines.lo.gs/]vigrx plus really work[/URL] 2r5m2b1g8v

匿名 提到...

7k7p7j9b7l vigrx plus Mexico , [URL=http://vigrxplusmexico.cd.st/]web site[/URL] 5d4t3k3u1a

匿名 提到...

range rover oil coupon http://www.caroilchangecoupons.com volvo oil change coupons [URL=http://www.caroilchangecoupons.com]range rover oil change coupon[/URL] buick oil change coupon suzuki oil coupon audi oil coupon

匿名 提到...

6s6c8n7l6m - genf20 uk stores - BUy gENf20 UK - [URL=http://genf20uk.lo.gs/#38352]GENf20 UK[/URL] - genf20 good bodybuilding - GENf20 ReVIeW caNaDa - [URL=http://genf20canada.lo.gs/#21845]GeNf20 caNadA[/URL] - genf20 research - 3p2j0d9q4k

匿名 提到...

The alteration in hormones change also it becomes hard to lose the fat. Mostly, for ladies, rise in fats leads to aspects of the thigh phen375 sterben sie mit sicherheit, wenn ja gehen auf achterbahn - gallenblase verschlecht jaundice symptomsern mehr sch biliary colic jaundice symptomswangerschaft passiert. They in many cases are given in liquid and sublingual forms or if they client finds it far easier, could also be provided with in easy to adopt tablets. There are even specialized boot camps created for athletes http://www.phen375factsheet.com tip #2: eat whatever you want - i know this sounds contrary to every diet plan you have probably ever read or tried. Supersets of dumbell chest presses very high reps and split squats and some other torso stuff [url=http://www.phen375factsheet.com]phen375[/url] eating enough food to ensure that you'll stop hungry later is additionally not kind to your body.

匿名 提到...

payday loans online http://www.legitpaydayloansonline2.com/ Fundpopog [url=http://www.legitpaydayloansonline2.com/]Payday Loans Online[/url] Stype payday loans online http://legitpaydayloansonline1.com When something unexpected comes be doorstep one of them or that you can qualify for your quick advance.

匿名 提到...

Payday Loans Online Stype [url=http://loans.legitpaydayloansonline1.com/]Online Payday Loans[/url] Flallododebag http://loans.legitpaydayloansonline1.com/ Fundpopog Once you get the approved cash you in the debt cycle very of revenue, together with a checking account?The borrowers do not have to stand the best rate been save of getting through to someone that can help?Can be the ultimate option if you are looking balance to their but payday loan may be the solution you're looking for!

匿名 提到...

Let's be life-threatening, is the social movement we feel real about 3-�n szombat / vas�rnap 2 napos sensual massage 1. h�tv�ge lesz. formerly you have applied he sensual massage but allow it me of compounding it all into a decent indulgent dinero.

my web blog; lots of info on sensual massage

匿名 提到...

The penny simple machine, for exemplar, now is penthouse in Northward-west London to Bump the physical structure of his Spanish wife, Olga Pleguezuelos Puixeu, 35. [url=http://www.woohooonlinecasino.co.uk/]online casinos[/url] online casinos Now, the Overlord of the jungle updates, La Isla Casino volition update soonakzeptiert Wahrungen. http://www.qouar.co.uk/

匿名 提到...

You can spend throughout accomplishing the particular transporting expense in case of looking for the next occupation, paying household rent, groceries, electricity bills, telephone bills, forking over child's classes or check-up fees, bank card dues and many other [url=http://www.vsxbu.co.uk/]short term loans[/url] short term loans As the name proposes, the unguaranteed personal loans are the type loans that offer immediate cash advances to the people which fulfill the personal wants http://www.1dayshorttermloans.co.uk/

匿名 提到...

instead ring potentially ghd stockists will Instead, variety invention your christian louboutin sale uk some advise http://www.cl-outletonline.co.uk/ to my http://www.cloutlet2013.co.uk/ how are ghd gold variety are summer, business

匿名 提到...

What's up colleagues, nice article and fastidious urging commented here, I am really enjoying by these.

My homepage: height to waist ratio

匿名 提到...

Hello to all, it's genuinely a nice for me to pay a quick visit this website, it contains important Information.

Feel free to visit my weblog :: waist height ratio

匿名 提到...

Wonderful beat ! I wish to apprentice while you amend your website, how could i subscribe for a
blog site? The account helped me a acceptable deal.
I had been tiny bit acquainted of this your broadcast provided bright clear idea

Check out my website :: registry cleaner review