ccommentsstrstr

Ignore comments from a line read with strstr in C


I have to write a code without third-party libraries that read from a file row by row and look for a switch or case operator. So far my code for that is this:

while(fgets(st, 1001, f1))
{
    lineCnt++;
    if(strstr(st, "switch"))
    {
        if(!strstr(st, "\""))
              switchCnt++;
    }
    if(strstr(st, "case"))
    {
        if(!strstr(st, "\""))
        caseCnt++;
    }
}

Which basically looks if on a given line there's a quote and if there is, don't increase the switch count. I think this covers most of the cases since I don't think there's gonna be a quote on a row with an actual switch operator, but I'm open for ideas on that part as well. I've done the same for the case counter as well.

How to ignore the comment parts of the file reading, since if there's let's say //switch count it's gonna be counted?


Solution

  • To cut comments, cut comments.

    If you simply want to cut all things after //, it will be:

    while(fgets(st, 1001, f1))
    {
        char* comment = strstr(st, "//");
        if (comment != NULL) *comment = '\0';
    

    Note that this cut will also applied to, for example, "hoge///";switch. (I don't know the syntax of the file to be deal with, so I cannot tell if this behavior is OK or not)