删除C/C++文件中的注释(c实现)

/**@author: yangjin  *
 * @date: 2012-7-27
 * @funciton: delete all comments in a c file
 */

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

main(void)
{
	FILE *fp1, *fp2;
	char c;
	if((fp1 = fopen("1.c", "r")) == NULL)
	{
		perror("open failed!\n");
		exit(-1);
	}
	if((fp2 = fopen("2.c", "w")) == NULL)
	{
		perror("open failed!\n");
		exit(-1);
	}
	while(!feof(fp1))
	{
		fscanf(fp1, "%c", &c);
		/*mean comments may start*/
		if(c == '/') 
		{
			fscanf(fp1, "%c", &c);
			if(c == '/')//mean '//'
			{
				while(c != '\n' && !feof(fp1))//delete until end of line
					fscanf(fp1, "%c", &c);
				if(c == '\n')
					fprintf(fp2, "%c", c);
			}		
			else if(c == '*')//mean '/*', so delete until meet '*/'
			{
				while(!feof(fp1))
				{	
					fscanf(fp1, "%c", &c);
					if(c == '*')
					{
						fscanf(fp1, "%c", &c);
						if(c == '/')//until meet '*/'
							break;
					}
				}
				
			}
			else
			{
				fprintf(fp2, "%c", c);
			}
				
		}
		/*constant string with "" need to keep*/
		else if(c == '\"')
		{
		    fprintf(fp2, "%c", c);//keep first "
			do{
				fscanf(fp1, "%c", &c);
				fprintf(fp2, "%c", c);
			}while(c != '\"' && !feof(fp1));
		}
		/*single constant char with '' need to keep*/
		else if(c == '\'')
		{
			fprintf(fp2, "%c", c);
			fscanf(fp1, "%c", &c);
			fprintf(fp2, "%c", c);
			fscanf(fp1, "%c", &c);
			fprintf(fp2, "%c", c);
		}
		/*normal c statement*/
		else
		{
		    fprintf(fp2, "%c", c);
		    /*
			while(c != '/' && c != '\"' && c != '\'' && !feof(fp1))
			{
				fscanf(fp1, "%c", &c);
				fprintf(fp2, "%c", c);
			}
			*/
		}
		
	}
	return 0;
}


你可能感兴趣的:(删除C/C++文件中的注释(c实现))