Tyler Lambert
Tyler Lambert

Reputation: 35

Searching a string in a binary file in C

In this code snippet I'm trying to add a string in a binary file. If the string already exists, I return error, otherwise I add it at EOF. I creataed two functions, void AddNewTeam(FILE* fp, char* newTeam), and int SearchTeam(FILE* fp, char* newTeam) as shown below, but that didn't work. Everytime I enter a string, it is added at EOF, even if is in the binary file. I think the problem is the fread function, I tried to print the value returned by the fread but it is always 0. Can someone help me trying to understand what's wrong with this code and why it's not working?

void AddNewTeam(FILE* fp, const char* newTeam){
    int found;

    if((fp = fopen("File.dat", "rb")) == NULL){
        fp = fopen("File.dat", "ab");
        fclose(fp);
    }
            
    printf("\tEnter New Team: ");
    scanf("%s", newTeam);
            
    found = SearchTeam(fp, newTeam);
            
    if(found == 0){
        if((fp = fopen("File.dat", "ab"))){
            fwrite(newTeam, sizeof(newTeam), 1, fp);
            printf("\tThe following team has been successfully loaded\n");
            fclose(fp);
        }
    }else if(found == 1){
        printf("\tThis team already exists\n");
        exit(EXIT_FAILURE);
    }
}

int SearchTeam(FILE* fp, const char* newTeam){
    char string[MAX][MAX_LENGTH];
    int counter, result, found = 0;
    if((fp = fopen("File.dat", "rb"))){
        fseek(fp, 0, SEEK_SET);
        for(counter = 0; !feof(fp); counter++){
            if(fread(string[counter], sizeof(string[counter]), 1, fp) == 1){
                result = strcmp(newTeam, string[counter]);
                if(result == 0){
                    found = 1; break;
                }else if(result != 0){
                    found = 0;
                }       
            }
        }
        fclose(fp);
        return found;
    }else if(fp == NULL){
        printf("\tError opening binary file\n");
        exit(EXIT_FAILURE);
    }
}

This is the main function and the function prototypes

int SearchTeam(FILE* fp, const char* newTeam);
void AddNewTeam(FILE* fp, const char* newTeam);

int main(void){
    FILE* fp;
    char newTeam[MAX_LENGTH];
    AddNewTeam(fp, newTeam);
    return 0;
}

Upvotes: 0

Views: 1346

Answers (1)

Barmar
Barmar

Reputation: 781004

You're not appending to the file correctly. The search code expects each team name to be in a block of MAX_LENGTH bytes. But when you write, you do:

fwrite(newTeam, sizeof(newTeam), 1, fp);

newTeam is a pointer, not an array, so sizeof will be the size of a pointer, typically 4 or 8 bytes. You need to write MAX_LENGTH bytes so this will match the way you read from the file.

fwrite(newTeam, MAX_SIZE, 1, fp);

Upvotes: 3

Related Questions