/* 本程序是在原有的c文件上删除注释,并不是将源文件中的注释删除然后将无注释的内容存放在新的文件中 */ 

运行环境是在linux上

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>


int main(int argc, const char *argv[])
{

	int file_size;
	if (2 != argc)
	{
		printf("usage:%s \n",argv[0]);
		return -1;
	}

	int fd = open(argv[1], O_RDWR);
	if (fd < 0)
	{
		puts("open error");
		return -1;
	}
	
	file_size = lseek(fd, 0, SEEK_END);
	/* 将文件映射到内存中,方便直接操作 */
	char *str = mmap(NULL, file_size,PROT_READ | PROT_WRITE , MAP_SHARED, fd, 0);
	if (NULL == str)
	{
		puts("mmap error");
		return -1;
	}
	char *p,*q;
	p = q = str;
	
	while( EOF != *p )
	{
		/* 处理行注释 */
		if ( ( '/' == *p ) && ( '/' == *(p+1) ) )
		{
			q = p;
			while( '\n' != *q)
			{
				*q++ = ' ';
				 
			}
			p = q;

		}/* 处理段落注释 */
		else if ( ('/' == *p) && ( '*' == *(p+1) ) )
		{
			q = p;
			while ( !( (*q == '*') && ( *(q+1) == '/')  ) )
			{
				*q++ = ' ';
			}
			/* 处理段落注释最后的"* /" */
			if ( (*q == '*') && ( *(q+1) == '/') )
			{
				*q++ = ' ';
				*q++ = ' ';
			}

			p = q;

		}
		else
			p++;
	}


	return 0;
}




 

 

Logo

更多推荐