I need to clear up non-active users from a directory and for that purpose I am creating the following function.
I currently have two lists: usernames (file1) and email (file2) addresses on individual lines. I need to find if the username from file1 exists in the email address list from file2.
These are the steps I have considered:
- Read the first username from file1 and remove the newline character.
- Start reading the email addresses from the file2, split at the "@" symbol and compare.
- If compare is succeeded, insert "##" sign in front of the username in the file1. (How can this be achieved?)
Problem
(Resolved by @MC93 answer)I am currently stuck at step 2. My program is only comparing the first username from the file1 and then stops comparing. Program exists normally.
Current Issue is Step3 and Improvements!!
Also, should I read the file2 split the words and store them in a sorted balanced tree to improve perfomance. If not, any other suggestions.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ( int argc, char** argv )
{
FILE * file1;
FILE * file2;
char * lineFromFile1 = NULL;
char * lineFromFile2 = NULL;
size_t len = 0;
ssize_t read1, read2;
char * token;
char * search = "@";
file1 = fopen("username.txt", "r");
file2 = fopen("email.txt", "r");
if ( file1 == NULL || file2 == NULL )
{
exit(EXIT_FAILURE);
}
while ((read1 = getline(&lineFromFile1, &len, file1)) != -1)
{
// Removing the newline character
if (lineFromFile1[strlen(lineFromFile1)-1] == '\n')
{
lineFromFile1[strlen(lineFromFile1)-1] = '\0';
}
printf("\nCurrent Username: %s \n", lineFromFile1);
// Reading email addresses and comparing
while ((read2 = getline(&lineFromFile2, &len, file2)) != -1)
{
// Splitting string at the '@' sign
token = strtok(lineFromFile2, search);
// Comparing strings
if ( strcmp(lineFromFile1, token) == 0)
{
printf("%s from File1 exists in File2 \n", lineFromFile1);
}
token = strtok(NULL, lineFromFile2);
token = NULL;
}
rewind(file2);
}
fclose(file1);
fclose(file2);
if ( lineFromFile1 || lineFromFile2 || token)
{
free(lineFromFile1);
free(lineFromFile2);
free(token);
}
}
File Contents
File1 File2
username email
janedoe johndoe@google.com
johndoe janedoe@google.com
Current Username: janedoe
janedoe from File1 exists in File2
Current Username: johndoe
RUN FINISHED; exit value 0; real time: 10ms; user: 0ms; system: 0ms