0

Hi make code at c which find string in txt file My code has as result how many times found the string and pos from the first character But i want colour the string in the txt file when find string but i had no idea how i can do that the code:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

main()
{
    FILE*fp;
    char fname[100];
    char data[20];
    char choice;
    char key[10];
    char*ptr;
    int counter=0;
    int pos_start;
    printf("Program start-up....\n");
    printf("Enter file name: ");
    gets(fname);
    fp=fopen(fname,"r");
    if (fp==NULL)
    {
        printf("Error:File can not be opened\n");
        printf("program closed...\n");
        exit(1);
    }
    printf("File is opened successfully\n");
    printf("Do you want search for string(y/n)");
    scanf(" %c",&choice);
    while ((choice!='y') && (choice!='n'))
    {
        printf("Do you want search for string(y/n)");
        scanf(" %c",&choice);
    }
    if (choice=='n')
    {
        printf("Search cancelled\n");
        printf("Program closed...\n");
        exit(1);
    }
    if (choice=='y')
    {
        printf("Search start-up...\n");
        printf("Please insert word: ");
        scanf("%s",key);
        while(!feof(fp))
        {
            fgets(data,sizeof(data),fp);
            ptr = strstr(data,key);
            while(ptr!=NULL)
            {
                counter++;
                pos_start=(ptr-data);
                printf("Position: %d\n",pos_start);
                ptr= strstr(ptr+1,key);
            }
        }
    }
    if (counter==0)
        printf("Word not found\n");
    if(counter>0)
        printf("Word: %s found: %d times\n",key,counter);
    printf("Search end\n");
    printf("Progarm closed...\n");
    fclose(fp);
    return 0;
}
AntonH
  • 6,359
  • 2
  • 30
  • 40

1 Answers1

0

You cant, a text file is a text file, it contains only the characters and has no formatting (colors, fonts, etc...) whatsoever

You might want to look at other text file formats for your output, for example: HTML.

EDIT :

If you want to output the result to a console instead of a file, some terminals supports the ANSI colors code. Since it is off-topic (you asked for writing a file), you can refer to this SO question for printing colors on the terminal.

Community
  • 1
  • 1
quantdev
  • 23,517
  • 5
  • 55
  • 88