Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have to write a code to check if an ID already exists in a file.

What I have tried:

This is the code i wrote :

printf("Please enter the ID of the student : ");
        scanf("%d", &newstudentID);
        printf("\n");
        input= fopen("stData.txt", "r");
        while((fread(buffer, sizeof(int), 6, input))!= EOF){
            strcmp(newstudentID, buffer) == diff;
            if(diff=0){
                printf("This student already exists.");
            }


When I run the code, it prompts me to enter the ID, when I do enter an ID the code simply crashes.
Posted
Updated 21-Mar-22 5:23am
Comments
jeron1 21-Mar-22 11:22am    
You should post the entire code if possible.

1 solution

So we have
C
scanf(%d, &newstudentID)
so presumably newstudentID is of type int. Then a bit later we have
strcmp(newstudentID, buffer)
Here, we are passing an int to strcmp as the first argument, but strcmp() is expecting a char *. So strcmp() uses whatever the student ID is as an address into memory - perhaps 42, which is almost certainly not an address that you have read access to, and tries to use that as a starting point for a string. Bad Things happen at this point.
There's no reason you can't use fscanf() to read "stData.txt" e.g.
C
int testID;
while( fscanf(input, "%d", &testID) {
    if(testID == newstudentID) {
       printf("ID already in use\n");
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900