If you are matching user names and passwords then you do not want to use strncmp. You should make sure they match exactly. You might find that when reading the input leaves new line characters or carriage returns in the buffer. If this is the case, I find it often is, then write yourself a function to remove them. Here is one way you can do it that is not particularly high performance :
void RemoveNewLines( char * buffer )
{
char * ptr;
ptr = strchr( buffer, '\n' );
if( ptr )
* ptr = 0;
ptr = strchr( buffer, '\r' ); if( ptr )
* ptr = 0;
}
You can then revise your code to look like this :
#define STRING_SIZE 49
int main()
{
char instr[STRING_SIZE+1];
char string[STRING_SIZE+1];
FILE * fr = NULL;
int flag = 0;
fr = fopen("fiile.csv","r");
if( fr == NULL )
{
printf( "Unable to open file\n" );
return 1;
}
printf("Enter your name: ");
fgets( instr, STRING_SIZE, stdin);
RemoveNewLines( instr );
while( fgets( string, STRING_SIZE, fr ) )
{
RemoveNewLines( string );
if( strcmp( instr, string ) == 0 )
{
printf("Here is your details");
printf("%s", string);
flag = 1;
break;
}
}
fclose(fr);
if( flag != 1 )
{
printf("Access denied.\n");
return -1;
}
return 0;
}
I think I see a potential problem with this. If your file is really a .CSV and you have other items on the same line (the details) then this will never match. However you can't just do a limited match. The two names "Jon" and "Jonathan" could possibly match if done on a limited basis so that is a problem.
To work around that issue, assuming the user name is followed by a comma in the file, you can try appending a comma to the user's entry. Then that would force the two to match up to the comma which should provide an exact match of user names. That revision could look like this :
#define STRING_SIZE 49
int main()
{
char instr[STRING_SIZE+1];
char string[STRING_SIZE+1];
FILE * fr = NULL;
int flag = 0;
size_t length = 0;
fr = fopen("fiile.csv","r");
if( fr == NULL )
{
printf( "Unable to open file\n" );
return 1;
}
printf("Enter your name: ");
fgets( instr, STRING_SIZE, stdin);
RemoveNewLines( instr );
strcat( instr, "," ); length = strlen( instr );
while( fgets( string, STRING_SIZE, fr ) )
{
RemoveNewLines( string );
if( strncmp( instr, string, length ) == 0 )
{
flag = 1;
break; }
}
fclose(fr);
if( flag == 1 ) {
printf( "Your details :" );
printf( "'%s'\n", string );
return 0;
}
printf("Access denied.\n");
return -1;
}
With the comma appended a limited string comparison makes sense assuming the name is followed by a comma in the file.