int count_operators(char* line) { int count = 0; int len = strlen(line); for (int i = 0; i < len; i++) { if (line[i] == ';') { count++; } } return count; }
int count_if_else(char* line) { int count = 0; int len = strlen(line); for (int i = 0; i < len; i++) { if (line[i] == 'i' && line[i+1] == 'f' && line[i+2] == '(') { count++; while (line[i] != ')') { i++; } if (line[i+1] == '{') { count++; } } else if (line[i] == 'e' && line[i+1] == 'l' && line[i+2] == 's' && line[i+3] == 'e') { count++; if (line[i+4] == '{') { count++; } } } return count; }
void read_and_write() { char program_filename[50]; char result_filename[50]; printf("Enter the name of the program file (.c): "); scanf("%s", program_filename); printf("Enter the name of the result file: "); scanf("%s", result_filename);
FILE* program_fp = fopen(program_filename, "r"); if (program_fp == NULL) { printf("Error opening program file\n"); return; }
FILE* result_fp = fopen(result_filename, "w"); if (result_fp == NULL) { printf("Error opening result file\n"); fclose(program_fp); return; }
int operator_count = 0; int if_else_count = 0; char line[100]; while (fgets(line, 100, program_fp) != NULL) { operator_count += count_operators(line); if_else_count += count_if_else(line); }
fprintf(result_fp, "Number of operators: %d\n", operator_count); fprintf(result_fp, "Number of if and if-else statements: %d\n", if_else_count);
printf("Result written to file %s\n", result_filename);
fclose(program_fp); fclose(result_fp); }
void read_and_print() { char filename[50]; printf("Enter the name of the program file (.c): "); scanf("%s", filename);
FILE* fp = fopen(filename, "r"); if (fp == NULL) { printf("Error opening program file\n"); return; }
int operator_count = 0; int if_else_count = 0; char line[100]; while (fgets(line, 100, fp) != NULL) { operator_count += count_operators(line); if_else_count += count_if_else(line); }
printf("Number of operators: %d\n", operator_count); printf("Number of if and if-else statements: %d\n", if_else_count);
fclose(fp); }
int main() { int choice; do { printf("\nMenu:\n"); printf("1. Read program from file and write result to file\n"); printf("2. Read program from file and print result to screen\n"); printf("3. Quit\n"); printf("Enter your choice: "); scanf("%d", &choice);
switch (choice) { case 1: read_and_write(); break; case 2: read_and_print(); break;