Подсветить идентификаторы с файла - C (СИ)
Формулировка задачи:
Вывести на экран содержимое файла с программой на С, подсвечивая другим цветом все идентификаторы.
Нашёл что-то похожее, но не работает:
#include <windows.h> #include <string.h> #include <stdio.h> int correct(char str[30], char gper[10][10]) { int k; k=1; for (int j=0; j<10; j++) { k=1; if (strlen(str)==strlen(gper[j])) { for (int i=0; gper[j][i] != '\0'; i++) { if (str[i] != gper[j][i]) k=0; } } else k=0; if (k==1) return(1); } if (k==1) return(1); else return(0); } void main () { FILE *in; char gper[10][10]; char str[50], word[30]; int i=0,k,j=0,beg,en,h; HANDLE consoleOutput; // Получаем хэндл консоли consoleOutput = GetStdHandle(STD_OUTPUT_HANDLE); consoleOutput= GetStdHandle (STD_OUTPUT_HANDLE); for (i=0;i<10;i++) for (j=0;j<10;j++) gper[i][j]='\0'; i=0; j=0; if ((in = fopen("prog.txt","r"))==NULL) { printf("Error at file opening. \n"); getchar(); getchar(); exit(1); } h=0; while (h!=1) { fgets(str, 50, in); for (k=0; str[k]!='\0'; k++) if (str[k]=='(') h=1; if (h!=1) { if (str[0] != '#') { k=0; while (str[k]!=' '&&str[k]!='\0') k++; k++; for (;;) { while (((str[k]<='z') && (str[k]>='a')) || ((str[k]<='Z') && (str[k]>='A'))) { gper[i][j]=str[k]; k++; j++; } i++; j=0; if (str[k]=='=') while ((str[k]!=',') && (str[k]!=';')) k++; else if (str[k]=='[') while ((str[k]!=',') && (str[k]!=';')) k++; else if (str[k]==',') k++; else if (str[k]==';') break; } } } } fclose(in); if ((in = fopen("prog.txt","rt"))==NULL) { printf("Error at file opening. \n"); getchar(); getchar(); exit(1); } i=0; while (!feof(in)) { beg=0; fgets(str, 50, in); for (int l=0; str[l] != '\0'; l++) { i=0; if ((l==0) && ((str[l]=='{') || (str[l]=='}'))) { printf(str); break; } if ((l==0) && (((str[l]<='z') && (str[l]>='a')) || ((str[l]<='Z') && (str[l]>='A')))) { while (((str[l]<='z') && (str[l]>='a')) || ((str[l]<='Z') && (str[l]>='A'))) { word[i]=str[l]; i++; l++; } word[i]='\0'; if ((correct(word,gper))==1) { SetConsoleTextAttribute (consoleOutput,BACKGROUND_RED | BACKGROUND_INTENSITY | FOREGROUND_GREEN); printf(word); SetConsoleTextAttribute (consoleOutput,BACKGROUND_RED | BACKGROUND_INTENSITY | FOREGROUND_GREEN); } else { printf(word); } beg=l; } else { if (((str[l]<='z') && (str[l]>='a')) || ((str[l]<='Z') && (str[l]>='A'))) { en=l-1; while (((str[l]<='z') && (str[l]>='a')) || ((str[l]<='Z') && (str[l]>='A'))) { word[i]=str[l]; i++; l++; } word[i]='\0'; if ((correct(word,gper))==1) { for (int r=beg; r<=en; r++) printf("%c", str[r]); SetConsoleTextAttribute (consoleOutput,BACKGROUND_RED | BACKGROUND_INTENSITY | FOREGROUND_GREEN); printf(word); SetConsoleTextAttribute (consoleOutput,BACKGROUND_RED | BACKGROUND_INTENSITY | FOREGROUND_GREEN); } else { for (int r=beg; r<=en; r++) printf("%c", str[r]); printf(word); } beg=en+1+strlen(word); } } } if (!((str[0]=='{') || (str[0]=='}'))) for (int r=beg; str[r]!='\0'; r++) printf("%c", str[r]); } fclose(in); getchar(); getchar(); }
Решение задачи: «Подсветить идентификаторы с файла»
textual
Листинг программы
#include "stdafx.h" #include <windows.h> #include <string.h> #include <stdio.h> #define KEYWORDS_LIST_SIZE (32) #define MAX_CONSOLE_WIDTH (80) #define MAX_CONSOLE_HEIGHT (25) static HANDLE _hConsole = INVALID_HANDLE_VALUE; enum COLORS { // Dark colors BLACK, BLUE, GREEN, CYAN, RED, MAGENTA, BROWN, LIGHTGRAY, // Light colors DARKGRAY, LIGHTBLUE, LIGHTGREEN, LIGHTCYAN, LIGHTRED, LIGHTMAGENTA, YELLOW, WHITE }; static char* pKeywords[KEYWORDS_LIST_SIZE] = { "auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "int", "long", "register", "return", "short", "signed", "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "volatile", "while" }; ////////////////////////////////////////////////////////////////////////// bool IsLetter(BYTE byChr) { if (((byChr <= 'z') && (byChr >= 'a')) || ((byChr <= 'Z') && (byChr >= 'A'))) { return true; } return false; } ////////////////////////////////////////////////////////////////////////// int FindKeyword(char* pszLine,int* piPos) { int iLen = strlen(pszLine); if (*piPos >= iLen) { return 0; } int iStart = *piPos; while (!IsLetter(pszLine[iStart])) { ++iStart; if (iStart >= iLen) { return false; } } int iSize = 0; *piPos = iStart; while (IsLetter(pszLine[iStart++])) { ++iSize; if (iStart >= iLen) { break; } } return iSize; } ////////////////////////////////////////////////////////////////////////// bool IsKeyword(char* pszLine,int iPos,int iSize) { for (int ii = 0; ii < KEYWORDS_LIST_SIZE; ++ii) { if (!strncmp(pKeywords[ii],&pszLine[iPos],iSize)) { return true; } } return false; } ////////////////////////////////////////////////////////////////////////// void TypeStr ( WORD wLine, // New Cursor Position Line WORD wCol, // New Cursor Position Column const char* const pszText // Pointer to Buffer to Write from ) { COORD ScrCoord; ScrCoord.Y = wLine; short iSize = (short)strlen(pszText); for (short iIdx = 0; iIdx < iSize; ++iIdx) { ScrCoord.X = (WORD)(wCol + iIdx); DWORD dwDummy; if (!FillConsoleOutputCharacter ( _hConsole, // Handle to a Console Screen Buffer pszText[iIdx], // Character to Write 1, // Number of Character Cells to Write to ScrCoord, // X- and Y-coordinates of First Cell &dwDummy // Pointer to Number of Cells Written to )) { // Error ! // Error(); } } } ////////////////////////////////////////////////////////////////////////// void Hilite ( WORD wLine, WORD wLeft, WORD wRight, WORD wColor // Foreground and Background Colors ) { COORD ScrCoord; WORD pwBuffer[MAX_CONSOLE_WIDTH]; ScrCoord.Y = wLine; ScrCoord.X = wLeft; DWORD dwCounter = (wRight - wLeft + 1); memset(pwBuffer,wColor,sizeof(WORD) * min(dwCounter,MAX_CONSOLE_WIDTH)); if (!WriteConsoleOutputAttribute ( _hConsole, // Handle to a Console Screen Buffer pwBuffer, // Pointer to Buffer to Write Attributes from dwCounter, // Number of Character Cells to Write to ScrCoord, // X- and Y-coordinates of First Cell &dwCounter // Pointer to Number of Cells Written to )) { // Error ! // Error(); } } ////////////////////////////////////////////////////////////////////////// int main(int argc,char** argv) { int iLine = 0; _hConsole = GetStdHandle(STD_OUTPUT_HANDLE); FILE* pInput = fopen("prog.txt","rt"); char pszLine[MAX_PATH + 1]; if (!pInput) { printf("Error at file opening.\n"); exit(-1); } while (!feof(pInput)) { fgets(pszLine,MAX_PATH,pInput); int iEolPos = strcspn(pszLine,"\r\n"); pszLine[iEolPos] = 0; // Remove EOL chars pszLine[MAX_CONSOLE_WIDTH] = 0; // Cut Here ! TypeStr((WORD)iLine,(WORD)0,pszLine); Hilite((WORD)iLine,(WORD)0,MAX_CONSOLE_WIDTH,YELLOW | (BLUE << 4)); int iPos = 0; int iSize = 0; while (iSize = FindKeyword(pszLine,&iPos)) { if (IsKeyword(pszLine,iPos,iSize)) { Hilite((WORD)iLine,(WORD)iPos,(WORD)(iPos + iSize),LIGHTGRAY | (BLUE << 4)); } iPos += iSize; } ++iLine; } fclose(pInput); getchar(); return 0; }