将合法 C 源程序每行前加上行号并删除其所有注释

#include
#include
#include
int main(void)
{
	char s1[199],row_number[4];
	int n, i, j, count,k;
	FILE *fp1, *fp2,*fp3;
	if( (fp1 = fopen( "delete_test.c", "r" )) == NULL )
	{
		printf("File open error!\n");
		exit(0);
	}
	if( (fp2 = fopen( "new_test.c", "w" )) == NULL )
	{
		printf("File open error!\n");
		exit(0);
	}
	while( !feof(fp1) )
	{
		count = 1;
		fgets(s1, 199, fp1);
		n = strlen(s1);
		for( i = 1; i < n; i++ )
		{
			if( s1[i] == '/' && s1[i-1] == '/' )
			{
				s1[i-1] = '\n';
				s1[i] = '\0';
				fputs( s1, fp2 );
				count = 0;
				break;
			}
			if( s1[i] == '*' && s1[i-1] == '/' )
			{
				s1[i-1] = '\n';
				s1[i] = '\0';
				fputs( s1, fp2 );
				count = 0;
				break;
			}
			if( s1[i] == '/' && s1[i-1] == '*' )
			{
				for( j = 0; j < n-i; j++ )
					s1[j] = s1[ j + i + 1];
				s1[j] = '\0';
				fputs( s1, fp2 );
				count = 0;
				break;
			}
		}
		if(count)
			fputs(s1, fp2);	
	}
	if(fclose(fp1))
	{
		printf( "Can not close the file!\n" );
		exit(0);
	}if(fclose(fp2))
	{
		printf( "Can not close the file!\n" );
		exit(0);
	}
	
	
	fp2 = fopen("new_test.c","r");
	fp3 = fopen("new_test_add.c","w");
	k=1;
	while(fgets(s1,199,fp2)!=NULL)
	{
		fprintf(fp3,"[%2d] ",k);
		fputs(s1,fp3); 
		k++;
	}
	if(fclose(fp2))
	{
		printf( "Can not close the file!\n" );
		exit(0);
	}if(fclose(fp3))
	{
		printf( "Can not close the file!\n" );
		exit(0);
	}
	return 0;
}

将合法 C 源程序每行前加上行号并删除其所有注释_第1张图片

去掉注释后

将合法 C 源程序每行前加上行号并删除其所有注释_第2张图片

最后加上行号

将合法 C 源程序每行前加上行号并删除其所有注释_第3张图片


最后感谢这位dalao    https://bbs.csdn.net/topics/392178701

你可能感兴趣的:(c)