我正在做一个项目,我必须在运行时动态填充的文件中捕获 ALIVE/SEARCH/BYEBYE 的 uuid 出现的统计信息(可以是全部 3 个,每个组合 2 个,或单独一个)。
我可以打印所有 3 种组合,但不能打印 1 或 2 种组合,例如
如果我的 input.txt 是这样的:
uuid:22314754-a597-490b-8a93-02cfae01036b ALIVE 16
uuid:22314754-a597-490b-8a93-02cfae01036b BYEBYE 8
uuid:22314754-a597-490b-8a93-02cfae01036b SEARCH 8
uuid:50e65653-7525-485d-83bf-d293558c4264 ALIVE 32
uuid:50e65653-7525-485d-83bf-d293558c4264 BYEBYE 8
uuid:50e65653-7525-485d-83bf-d293558c4264 SEARCH 132
uuid:55076f6e-6b79-4d65-6497-180373763bc1 ALIVE 113
uuid:55076f6e-6b79-4d65-6497-180373763bc1 BYEBYE 112
uuid:55076f6e-6b79-4d65-6497-180373763bc1 SEARCH 111
uuid:T0100203354 ALIVE 1
uuid:T0100203354 BYEBYE 2
uuid:T0100203354 SEARCH 3
我的代码:
#include<stdio.h>
#include<string.h>
struct uid
{
char uid_val[100];
char state[100];
int temp_count;
int alive_count;
int search_count;
int bye_count;
} UID[100];
int main()
{
char str[100];
int i = 0;
int line = 0;
char temp_val[100] = "waseem";
FILE *fp1 = fopen("input.txt","r");
FILE *fp2=fopen("output.txt","w");
printf("init value is %s \n",temp_val);
while(!feof(fp1))
{
fscanf(fp1,"%s %s %d",UID[i].uid_val,UID[i].state,&UID[i].temp_count);
int ret = 0;
ret=strcmp(UID[i].uid_val,temp_val);
if (ret!=0)
{
printf("new UID_val is %s\n",UID[i].uid_val);
}
else
{
}
temp_val[0] = '\0';
strcpy(temp_val,UID[i].uid_val);
if(strcmp(UID[i].state,"ALIVE")==0)
{
UID[i].alive_count = UID[i].temp_count;
}
else if(strcmp(UID[i].state,"BYEBYE")==0)
{
UID[i].search_count = UID[i].temp_count;
}
else
{
UID[i].bye_count = UID[i].temp_count;
}
line++;
if(line%3 == 0)
{
i++;
}
}
int n = 0;
//fp2=fopen("output.txt","w");
if (fp2==NULL)
{
printf("cant output to file\n");
}
else
{
fprintf(fp2,"Device ID\t\t\t\t\tALIVE\tBYEBYE\tSEARCH\n");
for(n = 0;n < i;n++)
{
fprintf(fp2,"%s\t%d\t%d\t%d\n",UID[n].uid_val,UID[n].alive_count,UID[n].search_count,UID[n].bye_count);
}
}
fclose(fp1);
fclose (fp2);
return 0;
}
}
给出以下输出:(output.txt)
Device ID ALIVE BYEBYE SEARCH
uuid:22314754-a597-490b-8a93-02cfae01036b 16 8 8
uuid:50e65653-7525-485d-83bf-d293558c4264 32 8 132
uuid:55076f6e-6b79-4d65-6497-180373763bc1 113 112 111
uuid:T0100203354 1 2 3
我想概括代码,使得 uuid 出现不必全部为 3(ALIVE/SEARCH/BYEBYE),出现可以是任何组合并且代码应该可以工作。例如,当 input.txt 包含以下内容时,我的代码给出了错误的结果:
uuid:22314754-a597-490b-8a93-02cfae01036b BYEBYE 8
uuid:22314754-a597-490b-8a93-02cfae01036b SEARCH 8
uuid:50e65653-7525-485d-83bf-d293558c4264 ALIVE 32
uuid:50e65653-7525-485d-83bf-d293558c4264 BYEBYE 8
uuid:55076f6e-6b79-4d65-6497-180373763bc1 ALIVE 113
uuid:55076f6e-6b79-4d65-6497-180373763bc1 BYEBYE 112
uuid:55076f6e-6b79-4d65-6497-180373763bc1 SEARCH 111
uuid:T0100203354 BYEBYE 2
我将 ubuntu 用于 gcc/g+ 编译器。