C程序从文件

时间:2018-05-24 03:49:17

标签: c

尝试执行以下程序时,它成功删除多行注释,但对于单行注释,它只是删除一个'/'。当调用c的函数(single_comment)值时,但是d的值是相同的'\'。由于这个完整的代码提供了输出'/'。请帮忙解决这个问题。

/*Program to remove all the comments from a c program */

#include<stdio.h>
#include<stdlib.h>

void check_comment(char);
void incomment();
void single_comment();

char c,d;
FILE *fp ,*fp1;


int main (int argc, char** argv)
{
    fp = fopen(argv[1],"r+");
    fp1 = fopen(argv[2],"w");


    if(fp == NULL)
    {
        perror("Error has occured");
        printf("Error occured.\n");
        exit(0);
    }

    fp1 = fopen(argv[2],"w");

    if(fp1 == NULL)
    {
        perror("Error has occured");
        printf("Error occured.\n");
        exit(0);
    }

    while((c = fgetc(fp)) != EOF)
    {
        check_comment(c);

    }

    fclose(fp);
    fclose(fp1);
}

void check_comment(char c)
{
    if (c == '/')
    {
        if((d = fgetc(fp)) == '*' )
        {
            incomment();
        }
        else if(d == '/')
        {
            single_comment();               
        }
        else
        {
            fputc(c,fp1);
            fputc(d,fp1);
        }
    }
    else
    {
        fputc(c,fp1);
        fputc(d,fp1);
    }
}

/* For removing multiline comments */

void incomment()
{
    c = fgetc(fp);
    d = fgetc(fp);

    while(c == '*' || c == '/')
    {
        c = d;
        d = fgetc(fp);
    }
}

//For removing single line comments`

void single_comment()
{
    char c,d;   
    while((c = fgetc(fp)) != EOF)
    {
        if (c == '\n')
            return;
    }
}

0 个答案:

没有答案