Skip to content

Instantly share code, notes, and snippets.

@ChinYikMing
Last active June 20, 2022 09:14
Show Gist options
  • Save ChinYikMing/7929aa41e881225bba88a3a9dec5ad64 to your computer and use it in GitHub Desktop.
Save ChinYikMing/7929aa41e881225bba88a3a9dec5ad64 to your computer and use it in GitHub Desktop.
remove /* */ and // comments in C programming language
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
/*
* @after_rm_comments_buf - buffer for removed file
* @src_file_name - source file for removing comments
* @return number of removed comments
*/
int rm_all_comments(char *after_rm_comments_buf, char *src_file_name);
/*
To execute the program, pass arguments like this:
./a.out src_file_for_removing_comments result_file_name
remark: result_file_name is exists does not matter
*/
int main(int argc, char *argv[]){
char *src_file_name = argv[argc - 2];
char *dest_file_name = argv[argc - 1];
int fd;
fd = open(src_file_name, O_RDONLY);
if(fd == -1){
printf("%s\n", strerror(errno));
return EXIT_FAILURE;
}
ssize_t buf_size;
buf_size = lseek(fd, 0, SEEK_END);
if(buf_size == -1){
printf("%s\n", strerror(errno));
return EXIT_FAILURE;
}
close(fd);
fd = open(dest_file_name, O_CREAT | O_WRONLY, 0777);
if(fd == -1){
printf("%s\n", strerror(errno));
return EXIT_FAILURE;
}
char result[buf_size];
int comments_cnt = rm_all_comments(result, src_file_name);
ssize_t write_size;
write_size = write(fd, result, strlen(result));
if(write_size == -1){
printf("%s\n", strerror(errno));
return EXIT_FAILURE;
}
printf("removed total %d comments\n", comments_cnt);
close(fd);
return EXIT_SUCCESS;
}
int rm_all_comments(char *after_rm_comments_buf, char *src_file_name){
FILE *file_ptr = fopen(src_file_name, "r");
if(file_ptr == NULL)
return -1;
int c;
int c1;
size_t idx = 0;
size_t comments_cnt = 0;
while((c = getc(file_ptr)) != EOF){
if(c == '/'){
check_again:
if((c1 = getc(file_ptr)) == EOF)
goto end;
else if(c1 != '*' && c1 != '/')
goto insert;
// invariant: a comment is found
comments_cnt++;
if(c1 == '/'){
// a double back slash comment is found
while((c = getc(file_ptr))){
if(c == EOF)
goto end;
else if(c == '\n')
goto insert;
}
}
// a /* */ comment is found
while((c1 = getc(file_ptr)) != '*' || (c1 = getc(file_ptr)) != '/');
// skip '/'
c = getc(file_ptr);
if(c == '/')
goto check_again;
}
insert:
after_rm_comments_buf[idx++] = c;
}
after_rm_comments_buf[idx] = '\0';
end:
fclose(file_ptr);
return comments_cnt;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment