#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define BUF_SIZE 64
int main(int argc, char **argv)
{
FILE *inFilePtr;
char fileName[BUF_SIZE];
char previous_char = ' ';
char current_char;
int is_quote_opening = 0;
int is_comment_opening = 0;
puts("Enter file name for checking comments: ");
scanf("%s", &fileName);
int line = 1; //Mục đích là để xuất ra vị trí bắt đầu của comment trong trường hợp không đóng comment
if((inFilePtr = fopen(fileName, "r")) != NULL)
{
FILE *outFilePtr;
if((outFilePtr = fopen("result.txt", "w")) != NULL)
{
while((current_char = fgetc(inFilePtr)) != EOF)
{
if(current_char == '"' && is_comment_opening == 0)
{
if(is_quote_opening == 0)
{
fputc(current_char, outFilePtr);
is_quote_opening = 1;
}
else if(is_quote_opening == 1)
{
fputc(current_char, outFilePtr);
is_quote_opening = 0;
}
}
else if(current_char == '*' && previous_char == '/')
{
is_comment_opening = 1;
}
else if(current_char == '/' && previous_char == '*')
{
is_comment_opening = 0;
}
else
{
if(is_quote_opening == 1)
{
fputc(current_char, outFilePtr);
}
else if(is_comment_opening == 1)
{
//Don't do anything
}
else if(current_char == '/')
{
//Temporarily skip
previous_char = current_char;
continue;
}
else
{
if(previous_char == '/')
{
fputc(previous_char, outFilePtr);
}
fputc(current_char, outFilePtr);
}
}
previous_char = current_char;
}
fclose(outFilePtr);
if(is_quote_opening == 1)
{
puts("Error, quotes doesn't close");
}
if(is_comment_opening == 1)
{
puts("Error, comments doesn't close");
}
fclose(inFilePtr);
}
else
{
}
}
else
{
//Báo lỗi
}
}
Em đang thử tiếp cận theo cách anh nói để giải quyết tiếp.
Theo diễn giải thì em nghĩ là nếu vị trí current_char = ‘/’ thì em đã tạm thời chuyển previous_char = current_char, sau đó continue vòng lặp mà không xét đến if cuối cùng.
Bởi vì nếu xét ở giai đoạn này thì is_comment_opening sẽ luôn đúng.
Khi đến trường hợp là mở block comment, thì is_comment_opening đã bắt đầu chuyển sang giá trị 1 nên sẽ an toàn, nếu trong trường hợp không phải mở block thì em đã yêu cầu xuất giá trị phía trước vào file mới như anh bảo.
Kết quả: some / stuff
từ some/*d crazy d*/ stuff