Tokencc C
Tokencc C
c Page 1 of 4
#include <stdio.h>
#include <ctype.h>
#include <string.h>
// List of keywords
const char *keywords[] = {
"if", "else", "while", "for", "return", "int", "float", "void", "char", "double"
};
// Ignore comments
if (ch == '/') {
int nextChar = fgetc(source);
if (nextChar == '/') {
// Single-line comment
while (ch != '\n' && ch != EOF) {
ch = fgetc(source);
}
return getNextToken(source); // Ignore comment and get next token
} else if (nextChar == '*') {
// Multi-line comment
while (1) {
ch = fgetc(source);
if (ch == '*' && (ch = fgetc(source)) == '/') {
break;
}
if (ch == EOF) {
break;
}
}
return getNextToken(source); // Ignore comment and get next token
} else {
ungetc(nextChar, source);
}
}
// Handle strings
if (ch == '\"') {
int i = 0;
token.lexeme[i++] = ch;
ch = fgetc(source);
while (ch != '\"' && ch != EOF) {
token.lexeme[i++] = ch;
ch = fgetc(source);
}
token.lexeme[i++] = ch;
token.lexeme[i] = '\0';
token.type = TOKEN_STRING;
return token;
}
ungetc(ch, source);
token.lexeme[i] = '\0';
if (isKeyword(token.lexeme)) {
token.type = TOKEN_KEYWORD;
} else {
token.type = TOKEN_IDENTIFIER;
}
return token;
}
// Handle operators
if (isOperator(ch)) {
token.type = TOKEN_OPERATOR;
token.lexeme[0] = ch;
token.lexeme[1] = '\0';
return token;
}
// Unknown token
token.type = TOKEN_UNKNOWN;
token.lexeme[0] = ch;
token.lexeme[1] = '\0';
return token;
}
int main() {
FILE *source = fopen("sample1.c", "r");
File: /home/shahana/tokencc.c Page 4 of 4
if (source == NULL) {
printf("Error: Unable to open file.\n");
return 1;
}
Token token;
do {
token = getNextToken(source);
printToken(token);
} while (token.type != TOKEN_EOF);
fclose(source);
return 0;
}