title: Why do I keep getting "incorrect login details" in the following code?
body: <p>This is a practice code for a login system.</p>
  <pre><code>struct login
  {
      char username[30];
      char password[20];
  };
  void login (void);
  void registration (void);
  int main (void)
  {
      int option;
      printf(&quot;Press '1' to Register\nPress '2' to Login\n\n&quot;);
      scanf(&quot;%d&quot;,&amp;option);
      getchar();
      if(option == 1)
          {
              registration();
          }
      else if(option == 2)
          {
              login();
          }
  }
  void login (void)
  {
      char username[30],password[20];
      FILE *log;
      log = fopen(&quot;login.txt&quot;,&quot;r&quot;);
      if (log == NULL)
      {
          fputs(&quot;Error at opening File!&quot;, stderr);
          exit(1);
      }
      struct login l;
      printf(&quot;\nPlease Enter your login credentials below\n\n&quot;);
      printf(&quot;Username:  &quot;);
      printf(&quot;\n&quot;);
      fgets(username, 30, stdin);
      printf(&quot;\nPassword: &quot;);
      printf(&quot;\n&quot;);
      fgets(password, 20, stdin);
      while(fread(&amp;l,sizeof(l),1,log))
          {
          if(strcmp(username,l.username)==0 &amp;&amp; strcmp(password,l.password)==0)
              {   
                  printf(&quot;\nSuccessful Login\n&quot;);
              }
          else 
              {
                  printf(&quot;\nIncorrect Login Details\nPlease enter the correct credentials\n&quot;);
              }
          }
      fclose(log);
      return;
  }
  void registration(void)
  {
      char firstname[15];
      FILE *log;
      log=fopen(&quot;login.txt&quot;,&quot;w&quot;);
      if (log == NULL)
      {
          fputs(&quot;Error at opening File!&quot;, stderr);
          exit(1);
      }
      struct login l;
      printf(&quot;Welcome to UrBook. Please choose a username and password as credentials for system login.\nEnsure the username is no more than 30 characters long.\nEnsure your password is at least 8 characters long and contains lowercase, uppercase, numerical and special character values.\n&quot;); 
      printf(&quot;\nEnter Username:\n&quot;);
      scanf(&quot;%s&quot;,l.username);
      printf(&quot;\nEnter Password:\n&quot;);
      scanf(&quot;%s&quot;,l.password);
      fwrite(&amp;l,sizeof(l),1,log);
      fclose(log);
      printf(&quot;\nRegistration Successful!\n&quot;);
      printf(&quot;Press any key to continue...&quot;);
          getchar();
      login();
  }
  </code></pre>
  <p>I can't seem to figure out the problem in the code.
  It always shows incorrect login details no matter what I put in. As an example, I wrote login as abc, password as 123. And similarly with some different inputs, but the same error was being shown. I also tried to use fscanf instead of fgetf, but it didn't work.</p>