Reputation: 9
I have the following file:
username=teste1;
status=ONLINE;
username=teste2;
status=ONLINE;
username=teste3;
status=OFFLINE;
Where one of the lines represents the user name and the bottom line represents the user's status just like above.
I would like to search for a specific username and show its status. But I can't seem to get the right return.
For now I have the following code:
int isUserOnline(char *username) {
FILE *f;
f = fopen(FILE_NAME,"r");
int i = 0;
char line[MAX] = {'\0'};
char destiny[MAX] = {'\0'};
while(!feof(f)) {
bzero(destiny, sizeof(destiny));
fgets(line, sizeof(line), f);
valueAfterEquals(destiny, line);
if(strcmp(destiny, username)) {
bzero(destiny, sizeof(destiny));
fgets(line, sizeof(line), f);
valueAfterEquals(destiny, line);
printf("is: %s \n", destiny);
if(strcmp(destiny, "OFFLINE")) {
return 1;
}
else
return 0;
}
}
}
The code above should look for the username and check if it exists, if it is offline, return one;
The valueAfterEquals function is, just takes the value after the equal sign and assigns it to a string:
void valueAfterEquals(char * destiny, char * buffer){
int k = 0;
while(buffer[k] != '='){
k++;
}
int i = 0;
k++; //pular o '='
while(buffer[k] != ';'){
destiny[i] = buffer[k];
k++;
i++;
}
}
Upvotes: 0
Views: 100
Reputation: 120
I suggest using fscanf
or sscanf
. Consider the following example:
char exampleStr[] = "username=teste1;";
char username[64];
// TO DO: add error checking on sscanf
sscanf(exampleStr, "%*[^=]=%[^;]", username); // username now holds "teste1"
if (strcmp(username, targetUsername) == 0)
{
// usernames are equal, do whatever you want
}
Upvotes: 1