Advertisement
salron3

FileParser

Dec 23rd, 2016
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 10.54 KB | None | 0 0
  1. #ifndef _CRT_SECURE_NO_WARNINGS
  2. #define _CRT_SECURE_NO_WARNINGS
  3. #endif
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. //#include <ctype.h>
  9.  
  10. #define SIZE 256
  11. #define NAMES 128
  12.  
  13. // Прототипи на функциите използвани по долу
  14. int menu();
  15. void getFileName(char* fileName, int mode);
  16. void GetNumberOfLoops(FILE *inputFile, FILE *outputFile);
  17. void GetNumberOfComments(FILE* inputFile, FILE* outputFile);
  18. int FileToFile();
  19. int FileToScreen();
  20. int ScreenToFile();
  21. int ScreenToScreen();
  22.  
  23. int main()
  24. {
  25.     while (1)
  26.     {
  27.         switch (menu())
  28.         {
  29.         case 1:
  30.             FileToFile();
  31.             break;
  32.         case 2:
  33.             FileToScreen();
  34.             break;
  35.         case 3:
  36.             ScreenToFile();
  37.             break;
  38.         case 4:
  39.             ScreenToScreen();
  40.             break;
  41.         case 0:
  42.             exit(0);
  43.         default:
  44.             break;
  45.         }
  46.  
  47.         system("pause");
  48.         system("cls");
  49.     }
  50.     return 0;
  51. }
  52.  
  53. int menu()
  54. {
  55.     int i;
  56.  
  57.     printf(" ________________M A I N   M E N U_________________\n");
  58.     printf("|                                                  |\n");
  59.     printf("| 1. Open a .txt/.c file and write to a file       |\n");
  60.     printf("| 2. Open a .txt/.c file and write to the screen   |\n");
  61.     printf("| 3. Enter text and write to a file                |\n");
  62.     printf("| 4. Enter text and write to the screen            |\n");
  63.     printf("| 0. Exit                                          |\n");
  64.     printf("|__________________________________________________|\n");
  65.  
  66.     do //while (i<0 || i>4);
  67.     {
  68.         fflush(stdin);// Чисти буфера
  69.         printf("Select Option: ");
  70.         scanf("%d", &i);
  71.     } while (i<0 || i>4);// Позволява въвеждане на числа само между 0 и 4
  72.     return i;// Връщаме избраната стойност
  73. }
  74.  
  75. void getFileName(char* fileName, int mode) /// 1 TO OPEN A FILE TO READ /// 2 TO OPEN A FILE TO WRITE ///
  76. {
  77.     while (1)// Безкраен цикъл
  78.     {
  79.         fflush(stdin);
  80.         if (mode == 1) // Ако е подадено 1 ще се изисква потребителя да въведе име на файл за четене
  81.         {
  82.             printf("Enter File Name To Read (.c/.txt): ");
  83.             scanf("%s", fileName);      ///gets(fileName);
  84.  
  85.             if (fileName[strlen(fileName) - 4] == '.' && toupper(fileName[strlen(fileName) - 3]) == 'T' && toupper(fileName[strlen(fileName) - 2]) == 'X' && toupper(fileName[strlen(fileName) - 1]) == 'T')
  86.             {
  87.                 return;
  88.             }
  89.  
  90.             if (fileName[strlen(fileName) - 2] == '.' && toupper(fileName[strlen(fileName) - 1]) == 'C')// Проверка дали файла завършва на .С
  91.             {
  92.                 return;// Ако завършва се излиза от функцията
  93.             }
  94.         }
  95.  
  96.         if (mode == 2)// При мод 2 се въвежда име на файла за запис
  97.         {
  98.             printf("Enter File Name To Write (.c/.txt): ");
  99.             scanf("%s", fileName);      ///gets(fileName);
  100.  
  101.             if (fileName[strlen(fileName) - 4] == '.' && toupper(fileName[strlen(fileName) - 3]) == 'T' && toupper(fileName[strlen(fileName) - 2]) == 'X' && toupper(fileName[strlen(fileName) - 1]) == 'T')
  102.             {
  103.                 return;
  104.             }
  105.  
  106.             if (fileName[strlen(fileName) - 2] == '.' && toupper(fileName[strlen(fileName) - 1]) == 'C')
  107.             {
  108.                 return;
  109.             }
  110.         }
  111.     }
  112. }
  113.  
  114. void GetNumberOfLoops(FILE *inputFile, FILE *outputFile)
  115. {
  116.     int countOP = 0, i = 0, flag = 0, flag2 = 0;
  117.     char line[SIZE];
  118.     while (fgets(line, sizeof(line), inputFile) != NULL) //Четене ред по ред
  119.     {
  120.         for (i = 0; i < strlen(line); i++)
  121.         {
  122.  
  123.             if (line[i] == '\"' && !flag) flag = 1; // не търсим в къвичките
  124.             else if (line[i] == '\"' && line[i - 1] != '\\' && flag == 1) flag = 0;
  125.  
  126.             if (!flag && line[i] == '/' && line[i + 1] == '/') break; // при наличието на коментар спираме да четем реда
  127.  
  128.             if (!flag && line[i] == '/' && line[i + 1] == '*') flag = 2;// не търсим в големите коментари / *
  129.             else if (flag == 2 && line[i] == '*' && line[i + 1] == '/') flag = 0;
  130.  
  131.             if (line[i] == '\'' && !flag) flag = 3; // не търсим в апострофите;
  132.             else if (line[i] == '\'' && flag == 3) flag = 0;
  133.  
  134.             if (!flag){
  135.                 if (line[i] == 'f' && line[i + 1] == 'o' && line[i + 2] == 'r')    countOP++;// Проверка за for
  136.                 else if (line[i] == 'd' && line[i + 1] == 'o')// проверка за оператор do
  137.                 {
  138.                     flag2++;
  139.                 }
  140.                 else if ((line[i] == 'w' && line[i + 1] == 'h' && line[i + 2] == 'i' && line[i + 3] == 'l' && line[i + 4] == 'e') && flag2)// Проверка за оператор while
  141.                 {
  142.                     flag2--;
  143.                     countOP++;
  144.                 }
  145.                 else if ((line[i] == 'w' && line[i + 1] == 'h' && line[i + 2] == 'i' && line[i + 3] == 'l' && line[i + 4] == 'e') && flag2 == 0) countOP++;
  146.             }
  147.         }
  148.     }
  149.     fprintf(outputFile, "The number of operators 'For', 'While','Do/While' is: %d\n", countOP);// Запис на информацията
  150. }
  151.  
  152. void GetNumberOfComments(FILE* inputFile, FILE* outputFile) //Функция за броене на броя коментарите
  153. {
  154.     int numberOfComments = 0;
  155.     int multylineComment = 0;
  156.     char line[256];
  157.     char currentChar = ' ';
  158.  
  159.     while ((currentChar = fgetc(inputFile)) != EOF) //Чете докато не стигне край на файла
  160.     {
  161.         int i = 0;
  162.         while (currentChar != '\n' && currentChar != EOF)//Прочита 1 ред
  163.         {
  164.             line[i++] = currentChar; //записва в масива
  165.             currentChar = fgetc(inputFile);
  166.         }
  167.  
  168.         line[i] = '\0';
  169.         if (i != 0) //Ако има прочетен ред
  170.         {
  171.             for (size_t j = 0; j < i - 1; j++)
  172.             {
  173.                 if (line[j] == '/' && multylineComment == 0)
  174.                 {
  175.                     if (line[j + 1] == '/')
  176.                     {
  177.                         numberOfComments++;
  178.                     }
  179.                     else if (line[j + 1] == '*')
  180.                     {
  181.                         multylineComment = 1;
  182.                     }
  183.                 }
  184.                 else if (line[j] == '*' && line[j + 1] == '/')
  185.                 {
  186.                     multylineComment = 0;
  187.                     numberOfComments++;
  188.                 }
  189.             }
  190.         }
  191.     }
  192.     fprintf(outputFile, "Total comments: %d\n", numberOfComments); //Записване на информацията в изходният файл
  193. }
  194.  
  195. int FileToFile()
  196. {
  197.     char readFile[NAMES] = { 0 }, writeFile[NAMES] = { 0 }; // Имената на файловете
  198.     FILE* inputFile, *outputFile; // Деклариране на файлов поинтър
  199.     getFileName(readFile, 1);// Въвеждане на името на файла за четене
  200.  
  201.     inputFile = fopen(readFile, "r"); // Отваряме файла за четене. "r" за четене
  202.     if (inputFile == NULL)// Проверка дали съществува файла
  203.     {
  204.         fprintf(stderr, "ERROR! CANNOT OPEN FILE!!!");
  205.         return; // Връщаме се към main-а
  206.     }
  207.  
  208.     getFileName(writeFile, 2);// Въвеждане на файла за писане
  209.     outputFile = fopen(writeFile, "w");// Проверка дали е отворен/създанен файл
  210.  
  211.     if (outputFile == NULL)
  212.     {
  213.         fprintf(stderr, "ERROR! CANNOT OPEN FILE!!!");
  214.         return;// Връщаме се към main-а
  215.     }
  216.  
  217.  
  218.     GetNumberOfComments(inputFile, outputFile);//Викане на функцията за броене на коментари
  219.     rewind(inputFile);// Връща файловия поинтър към началото на файла(за да може пак да се прочете)
  220.     GetNumberOfLoops(inputFile, outputFile);//Викане на функцията брояща циклите
  221.     printf("Information saved to \"%s\"\n", writeFile);
  222.  
  223.     fclose(inputFile);//затваряне на файла
  224.     fclose(outputFile);
  225.  
  226.     return 0;
  227. }
  228.  
  229. int FileToScreen()
  230. {
  231.     char readFile[NAMES] = { 0 };
  232.     FILE* inputFile;
  233.     getFileName(readFile, 1);
  234.  
  235.     inputFile = fopen(readFile, "r");// Отваряне на файла за четене
  236.     if (inputFile == NULL)
  237.     {
  238.         fprintf(stderr, "CANNOT OPEN FILE!");
  239.         return;
  240.     }
  241.  
  242.     GetNumberOfComments(inputFile, stdout);// stdout e изходен поток за данни. Той превръща fprintf-a в обикновен printf
  243.     rewind(inputFile);// Връща файловия поинтър към началото на файла(за да може пак да се прочете)
  244.     GetNumberOfLoops(inputFile, stdout);
  245.  
  246.     fclose(inputFile);
  247.  
  248.     return 0;
  249. }
  250.  
  251. int ScreenToFile()
  252. {
  253.     char writeFile[NAMES] = { 0 }, manage[SIZE], c = 0;
  254.     FILE *outputFile, *tempBuffer;
  255.  
  256.     getFileName(writeFile, 2);// Въвеждане на името на файла за запис
  257.  
  258.     outputFile = fopen(writeFile, "w");//Отваря файла за писане
  259.     if (outputFile == NULL)// Проверка за дали файла е отворен(създаден)
  260.     {
  261.         fprintf(stderr, "CANNOT OPEN FILE!");// stderr поток за грешки
  262.         return;
  263.     }
  264.  
  265.     tempBuffer = fopen("TempChanges.tmp", "w");// Отваряне на временен файл за писане
  266.  
  267.     printf("\nWrite text under the line and type \"exit\" on a new line to save the information\n");
  268.     printf("________________________________________________________________________________\n");
  269.     fflush(stdin);
  270.  
  271.     while (1)
  272.     {
  273.         gets(manage);// Взима низ от клавиетурата
  274.         if (!strcmp(manage, "exit"))// Проверка дали се среща 'exit' във въведения от потребителя низ
  275.         {
  276.             fclose(tempBuffer);//ако се среща файла се затваря
  277.             tempBuffer = fopen("TempChanges.tmp", "r");// след това се отваря за четене
  278.             break;//излизане от безкрайният цикъл
  279.         }
  280.         fprintf(tempBuffer, "%s\n", manage);// Записване на низа въведен от потребителя
  281.     }
  282.  
  283.  
  284.     GetNumberOfComments(tempBuffer, outputFile);
  285.     rewind(tempBuffer);
  286.     GetNumberOfLoops(tempBuffer, outputFile);
  287.  
  288.     printf("Information saved to \"%s\"\n", writeFile);
  289.  
  290.     fclose(outputFile);
  291.     fclose(tempBuffer);
  292.  
  293.     return 0;
  294. }
  295.  
  296. int ScreenToScreen()// Тук нещата са като по-горе
  297. {
  298.     char  manage[SIZE], c = 0;
  299.     int counter = 0;
  300.     FILE *tempBuffer;
  301.  
  302.     tempBuffer = fopen("TempChanges.tmp", "w");
  303.  
  304.     printf("\nWrite text under the line and type \"exit\" on a new line to save the information\n");
  305.     printf("________________________________________________________________________________\n");
  306.     fflush(stdin);
  307.  
  308.     while (1)
  309.     {
  310.         gets(manage);
  311.         if (!strcmp(manage, "exit"))
  312.         {
  313.             fclose(tempBuffer);
  314.             tempBuffer = fopen("TempChanges.tmp", "r");
  315.             break;
  316.         }
  317.         fprintf(tempBuffer, "%s\n", manage);
  318.     }
  319.  
  320.     system("CLS");
  321.     printf("Information:\n");
  322.     GetNumberOfComments(tempBuffer, stdout);
  323.     rewind(tempBuffer);
  324.     GetNumberOfLoops(tempBuffer, stdout);
  325.  
  326.     fclose(tempBuffer);
  327.  
  328.     return 0;
  329. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement