my goal is to retrieve names from a file, save it to an array and save its changes as to program terminates. also, the user cannot add a name that already exists, despite of its case. can someone please tell me what's wrong with my code? it can't compare efficiently those names from the file to the ones which the user entered.. i tried everything i could do... thanks for all the help
here is a fragment of my code:
Code:
typedef struct{
char name[maxChar];
}namelist;
int ind = 1;
void addName(namelist names[], char aname[], int pos){
int i, comp = 0, ind2 = ind;
char temp[maxChar], temp2[maxChar];
strcpy(temp,addname);
for(i = 1; i < ind; i++){
strcpy(temp2,names[i].name);
if((strcmpi(temp, temp2))==0){
comp++;
}
}
if(comp == 0){
if(ind < pos || pos < 1) printf("\nWarning: Cannot add at position %d!\n",pos);
else if(ind > pos && ind != 1){
while(ind2 >= pos){
names[ind2 + 1] = names[ind2];
ind2--;
}
strcpy(names[pos].name, aname);
ind++;
}
else strcpy(names[ind++].name,aname);
}
else printf("\nWarning: %s is already in the list!\n",aname);
}
int main(){
int ch, pos, i;
namelist names[100];
char name[30], c[30];
FILE *file;
file = fopen("CRUSHLIST.txt", "r+");
printf("\nRetrieving CRUSHLIST.txt...\n");
if(file==NULL) {
printf("\nError: can't open file.\n");
exit(1);
}
else {
printf("\nFile opened successfully! Retrieving contents...\n");
for(i = 1; fgets(c, sizeof(c), file)!=NULL ; i++){
if(c[strlen(c)-1] == '\n') c[strlen(c)-1] = 0;
strcpy(names[i].name,c);
ind++; //else which is previously there was a typo.. my apologies
}
}
do{
ch = menu();
switch(ch){
case 1: printf("Enter name: ");
fgets(name,sizeof(name),stdin);
if(name[strlen(name)-1] == '\n') name[strlen(name)-1] = 0;
printf("Enter position: ");
scanf("%d",&pos);
addName(names,name,pos);
printf("\n");
break;
//some code here