#include<stdlib.h>
#include<stdio.h>
#define MAX_LINE_LENGTH 250
#define handle_c_comment(ch,sbuf)\
{\
while(1){\
if(*ch == '\0'){\
if(fgets(sbuf, MAX_LINE_LENGTH, infile) == NULL){\
fprintf(stderr, "Error: Probably syntax error becase reach EOF before the end of comment\n");\
exit(1);\
}\
ch = sbuf;\
}\
while(*ch != '/' && *ch != '\0'){\
fputc(*ch, outfile);\
++ch;\
}\
if(*ch == '\0') continue;\
else{\
fputc('/',outfile);\
if(*(ch-1) == '*'){\
++ch;\
break;\
}else{\
++ch;\
}\
}\
}\
}
#define handle_cpp_comment(ch,sbuf)\
{\
fputc('*',outfile);\
++ch;\
while(1){\
if( *ch == '\0'){\
if(fgets(sbuf, MAX_LINE_LENGTH, infile) == NULL){\
fputs("*/",outfile);\
exit(0);\
}else {\
ch = sbuf;\
}\
}\
while(*ch != '\n' && *ch != '\0' && *ch != '/'){\
fputc(*ch,outfile);\
++ch;\
}\
if(*ch == '\n'){\
fputs("*/\n",outfile);\
++ch;\
break;\
}else if (*ch == '/'){\
if(*(ch-1) == '*' ){\
fputs(" /",outfile);\
}else{\
fputc('/', outfile);\
}\
++ch;\
}\
}\
}
#define handle_string(ch,sbuf)\
{\
fputc('\"', outfile);\
++ch;\
while(1){\
if(*ch == '\0'){\
if(fgets(sbuf, MAX_LINE_LENGTH, infile) == NULL){\
fprintf(stderr, "Error: Probably syntax error becase reach EOF before the end of string\n");\
exit(2);\
}\
ch = sbuf;\
}\
while(*ch != '\"' && *ch != '\0'){\
fputc(*ch, outfile);\
++ch;\
}\
if(*ch == '\0') continue;\
else if(*ch == '\"'){\
fputc('\"', outfile);\
++ch;\
break;\
}\
}\
}
static int cmdargc=1;
static FILE* infile = NULL;
static FILE* outfile = NULL;
void close_opened_files(void );
int main(int argc, char * argv[])
{
char sbuf[MAX_LINE_LENGTH+1];
char* ch;
atexit(&close_opened_files);
if(argc == 1){
infile = stdin;
outfile = stdout;
}else if(argc == 2){
cmdargc = 2;
infile = fopen(argv[1], "r");
outfile = stdout;
}else if(argc == 3){
outfile = fopen(argv[2] ,"w");
infile = fopen(argv[1], "r");
cmdargc = 3;
}else{
fprintf(stderr, "Usage: %s [in_file], [out_file]",argv[0] );
exit(3);
}
while(fgets(sbuf,MAX_LINE_LENGTH,infile)){
ch = sbuf;
while(*ch != '\0'){
switch(*ch){
case '/':
fputc(*ch, outfile);
++ch;
if(*ch == '*'){
handle_c_comment(ch,sbuf);
}else if(*ch == '/'){
handle_cpp_comment(ch,sbuf);
}else{
fputc(*ch,outfile);
++ch;
}
break;
case '\"':
handle_string(ch,sbuf);
break;
default:
fputc(*ch,outfile);
++ch;
break;
}
}
}
exit(0);
}
void close_opened_files(void )
{
if(cmdargc == 2)
fclose(infile);
else if (cmdargc == 3){
fclose(outfile);
fclose(infile);
}
/* printf("All files closed\n ");*/
}
C++注释转换为C语言的注释
5星 · 超过95%的资源 需积分: 12 30 浏览量
2011-05-20
21:13:40
上传
评论 9
收藏 1KB GZ 举报
elie_001
- 粉丝: 2
- 资源: 16
- 1
- 2
前往页