C & C++ program to read from file and compare and then write to file


 Hi, here below is the program actually writen in c and i have made it available in c++, use this and enjoy.........


Source Code :

file name:  Readcomparewrite.cpp

#include "stdio.h"
#include <string.h>

int main()
{
FILE *fp1;
char user[20]="praneeth", passwd[20]="Passcode";
char oneword[20], str[2][20];
char c, uname[20], upwd[20];
int i=0;
   fp1 = fopen("test.txt","r");
   printf("==========================\nBefore closing file\n==========================\n");
     while(fscanf(fp1,"%s",oneword) != EOF)
    {
    printf("%s\n",oneword);
    strcpy(str[i],oneword);
    i++;  
     }
    fclose(fp1);
    printf("==========================\nafter closing file\n==========================\n");
      printf("str : %s\n",str[0]);
      printf("str : %s\n",str[1]);
    printf("==========================\nInput Strings\n==========================\n");
       printf("user : %s\npasswd : %s\n",user,passwd);
    printf("==========================\nComparing Strings\n==========================\n");
    if(strcmp(str[0],user)==0  &&  strcmp(str[1],passwd)==0 )
    {  printf("loggedin\n");    }
    else { if(strcmp(str[0],user)==0)
      { //printf("%d",strcmp(str[0],user));
        printf("password is wrong\n"); }
    else { if(strcmp(str[1],passwd)==0)
      { //printf("%d",strcmp(str[1],passwd));
        printf("username is wrong\n"); }
    else
      { printf("Username & Password are Wrong\n"); }
    } }
    printf("==========================\nEntering/Updating Strings in File\n==========================\n");
      fp1 = fopen("test.txt","w");
      fflush(stdin);
      printf("Enter Username (20 Charectors Only)");
      scanf("%s",uname);
      fflush(stdin);
      printf("Enter Password (20 Charectors Only)");
      scanf("%s",upwd);
      fprintf(fp1,"%s\n%s",uname, upwd);
      fflush(stdin);
      fclose(fp1);
     
    return 0;
}





file name : test.txt :


asdf
rfefd


Output :

[root@localhost cpp]# ./Readcomparewrite
==========================
Before closing file
==========================
praneeth
Passcode
==========================
after closing file
==========================
str : praneeth
str : Passcode
==========================
Input Strings
==========================
user : praneeth
passwd : Passcode
==========================
Comparing Strings
==========================
loggedin
==========================
Entering/Updating Strings in File
==========================
Enter Username (20 Charectors Only)praneeth
Enter Password (20 Charectors Only)passcode
[root@localhost cpp]#
 

Comments