Create a structure called account wit data member acc no., ac type n balance. Now write a program to store record of 20 acc in a file named customer.txt den display only those acc no. wit blc less than 500
Code: #include <stdio.h> #include <conio.h> #include <stdlib.h> typedef struct { int account_number; char account_type[30]; int balance; }account; void main() { struct account acc[5]; int i; for(i=0;i<5;i++) { printf("Enter Account Number : "); scanf("%d",&acc[i].account_number); printf("Enter Account Type : "); fflush(stdin); gets(acc[i].account_type); printf("Enter Balance : "); scanf("%d",&acc[i].balance); } FILE *ofp; for (i=0;i<5;i++) { printf("%d \n",acc[i].account_number); printf("%s \n",&acc[i].account_type); printf("%d \n",acc[i].balance); ofp = fopen("customer.txt", "wb"); fwrite(&acc[i], sizeof acc[i], 5, ofp); } fclose(ofp); system("cls"); printf("Account with balance higher then Rs.500/-"); printf("******************************************\n"); for(i=0;i<5;i++) { if(acc[i].balance>500) { printf("Record no. %d \n\n",i); printf("Account Number : "); printf("%d \n",&acc[i].account_number); printf("Account Type : "); printf("%s \n",&acc[i].account_type); printf("Balance : "); printf("Rs.%d \n",&acc[i].balance); printf("\n\n"); } } } this is all i could do...the struct is not written in the txt file... there must be some mistake... and actually the second output printing is to be done by reading the values from the txt file..but i have directly printed it..
Your fopen and fwrite shouldn't be inside the for loop, further if you check the documentation for fwrite()( you'll see you only need to call fwrite once, not five times.
i tried it...n something seems to be written in the customer.txt file... it looks something like this "Hÿ( ž@ 8@ àý~xÿ( K@ PR øR ÿÿÿÿpÿ( *v @ øR àý~ˆÿ( ˜@ ”ÿ( w6\v àý~Ôÿ( rw àý~ž32w àý~ *ÿ( ÿÿÿÿwš ìÿ( Ew€@ àý~ €@ àý~ " wats the problem here... here is the code: FILE *ofp; for (i=0;i<5;i++) { printf("%d \n",acc.account_number); printf("%s \n",&acc.account_type); printf("%d \n",acc.balance); } ofp = fopen("customer.txt", "w"); fwrite(&acc, sizeof acc, 5, ofp); fclose(ofp);
Of course you get junk. i at that point is 5, which is off the end of the array. You need to give fwrite the pointer to the START of the memory block to be written to the file.
What do you think will be the output of this code? If you're not sure, try it. Code: for (i=5;i<10;i++) { printf("%d \n",acc[i].account_number); printf("%s \n",&acc[i].account_type); printf("%d \n",acc[i].balance); } Also you might want to try this code so that you can see why I said i=5: Code: int i; for (i=0; i<5; i++) { printf("Inside loop, i=%d\n",i); } printf("After loop, i=%d\n",i);