learningc/chapters/1/exercises/shared/functions/uncomment.c

59 lines
1.4 KiB
C

#include <stdio.h>
int com = 0;
/*
* TODO:
* Keep backbuffer of 1 character (current & i-1) to check for comment ends
* Handle double slashes nicely
* Find a cleaner way to achieve this
*/
int uncomment(char s[],int lim) {
int c, i, quo = 0, wnl = 0;
/* c is character integer
* i is column
* com is current comment state
* quo is current quote state */
for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i) {
/* Check if we are in a character constant or between quotes, if yes ignore comments */
if (c == '"' || (c == '\'' && s[i-1] != '"')) {
if (quo == 1) {
quo = 0; //test
} else {
quo = 1;
}
} else if (quo == 0 && (c == '/' || c == '*')) {
if (com == 0) {
if (c == '*' && s[i-1] == '/') {
com = 1;
} else if (c == '/' && s[i-1] == '/') {
wnl = 1;
s[i-1] = ' ';
}
} else if (com == 1 && c == '/' && s[i-1] == '*') {
com = 0;
}
}
if (com == 0 && wnl == 0) {
s[i] = c;
} else {
s[i] = ' ';
}
}
/* If the line is completly empty, do not print a new line, jump to the next line */
for (;i > 0 && (s[i-1] == ' ' || s[i-1] == '\t'); i--);
if (i == 0) {
s[i] = '\0';
} else {
s[i] = '\n';
s[i+1] = '\0';
}
/* If we have hit the end of the line, tell the previous function, else return the lenght */
if (c == EOF) {
return EOF;
} else {
return i;
}
}