Advertisement
Sri27119

cd2 keywords

Nov 20th, 2024 (edited)
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.89 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <ctype.h>
  4.  
  5. // List of 32 C keywords
  6. const char *keywords[] = {
  7.     "auto", "break", "case", "char", "const", "continue", "default", "do",
  8.     "double", "else", "enum", "extern", "float", "for", "goto", "if",
  9.     "int", "long", "register", "return", "short", "signed", "sizeof",
  10.     "static", "struct", "switch", "typedef", "union", "unsigned", "void",
  11.     "volatile", "while"
  12. };
  13. #define NUM_KEYWORDS (sizeof(keywords) / sizeof(keywords[0]))
  14.  
  15. int is_keyword(const char *word) {
  16.     for (int i = 0; i < NUM_KEYWORDS; i++) {
  17.         if (strcmp(word, keywords[i]) == 0) {
  18.             return 1;
  19.         }
  20.     }
  21.     return 0;
  22. }
  23.  
  24. int main() {
  25.     FILE *file;
  26.     char filename[] = "input.txt";
  27.     char buffer[1000];
  28.     int keyword_count[NUM_KEYWORDS] = {0};
  29.  
  30.     file = fopen(filename, "r");
  31.     if (file == NULL) {
  32.         printf("Could not open file %s\n", filename);
  33.         return 1;
  34.     }
  35.  
  36.     printf("Content of %s:\n", filename);
  37.     while (fgets(buffer, sizeof(buffer), file)) {
  38.         printf("%s", buffer);
  39.  
  40.         // Process the current line for keywords
  41.         char *token = strtok(buffer, " \t\n.,;(){}[]<>+-/*&|^%=!~");
  42.         while (token != NULL) {
  43.             // Check if the token is a keyword
  44.             if (is_keyword(token)) {
  45.                 for (int i = 0; i < NUM_KEYWORDS; i++) {
  46.                     if (strcmp(token, keywords[i]) == 0) {
  47.                         keyword_count[i]++;
  48.                         break;
  49.                     }
  50.                 }
  51.             }
  52.             token = strtok(NULL, " \t\n.,;(){}[]<>+-/*&|^%=!~");
  53.         }
  54.     }
  55.  
  56.     fclose(file);
  57.  
  58.     printf("\n\nKeyword frequencies:\n");
  59.     for (int i = 0; i < NUM_KEYWORDS; i++) {
  60.         if (keyword_count[i] > 0) {
  61.             printf("%s: %d\n", keywords[i], keyword_count[i]);
  62.         }
  63.     }
  64.  
  65.     return 0;
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement