如何使用 C 在控制台中以彩色打印出被阻止的客户端

问题描述 投票:0回答:1

我正在尝试以不同的颜色打印所有客户。那些没有处于正常白色“阻止”状态的人,以及那些处于“阻止”状态的人应该在控制台中以红色打印出来。不过,我有一些格式,例如“—”破折号,但我无法使用它们,这意味着我想打印出从“BLOCKED”一词开始的被阻止的客户端,颜色为红色,直到最后一个破折号,而不是“注册日期” :'就像现在发生的那样。

           BLOCKED
         Client ID: 05300
—————————————————————————————————————
Name: ABC
—————————————————————————————————————
Last: DEF
—————————————————————————————————————
Date of reg: 22-12-2023 18:46:13   <-- this is where the color red ends
————————————————————————————————————  <-- but I want it to end here

//And this client is printed out in normal white color since he does not have status 'blocked'
        Client ID: 05796
—————————————————————————————————————
Name: ERT
—————————————————————————————————————
Last: TYU
—————————————————————————————————————
Date of reg: 22-12-2023 18:49:22
—————————————————————————————————————

我将输入的数据保存到这样的文件中:

fprintf(file, "\n        Client ID: %05d\n", rand() % 10000);
fprintf(file, "—————————————————————————————————————\n");
fprintf(file, "Name: %s\n", name);
fprintf(file, "—————————————————————————————————————\n");
fprintf(file, "Last: %s\n", last);
fprintf(file, "—————————————————————————————————————\n");
fprintf(file, "Date of reg: %s\n", formatted_date);
fprintf(file, "—————————————————————————————————————\n");

然后我从中读到:

    char line[100];
    bool blocked= false;
    rewind(file);
     
    printf("\nPRINTING OUT ALL CLIENTS:\n\n");
    while(fgets(line, sizeof(line), file))
    {
        if (strstr(line, "           BLOCKED") != NULL)
            blocked = true;

        
        if (blocked)
        {
            SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_INTENSITY);
            printf("%s", line);
        }
        else
        {
            SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | 
            FOREGROUND_INTENSITY);
            printf("%s", line);
        }

        if (strstr(line, "Date of reg:") != NULL)  //here is the problem
        {  
            blocked= false;        
        } 
        /* if(strstr(line, "—————————————————————————————————————" != NULL)
               blocked = false; */  this does not help
    }
}

那么我怎样才能以红色打印出被阻止的客户端,直到最后一个———————————————————————————————————— ———— 红色破折号?

c windows file winapi formatting
1个回答
0
投票

当您到达

Date of reg:
行时设置一个变量,以指示您已到达客户端的末尾。然后在打印分隔线后检查这一点。

    while(fgets(line, sizeof(line), file))
    {
        if (strstr(line, "           BLOCKED") != NULL) {
            blocked = true;

        SetConsoleTextAttribute(hConsole, FOREGROUND_RED | (blocked ? 0 : FOREGROUND_GREEN) | FOREGROUND_INTENSITY);
        printf("%s", line);
 
        if (strstr(line, "Date of reg:") != NULL)
        {  
            end_of_client = true;        
        } 

        if(end_of_client && strstr(line, "—————————————————————————————————————" != NULL) {
            blocked = false;
            end_of_client = false;
        }

    }
© www.soinside.com 2019 - 2024. All rights reserved.