Search code examples
cstructurefwrite

Why can't I see structure inserted record from files while opening it in editor?


I have a problem with structure handling in C files. Here I wrote this programme to save bank customer record into the file. It's working fine but when I'm trying to open the data file[.txt (or).dat].It's showing some binary digits. Below is my programme.

/* Reading bank details and saving it on a file and printing it on 
screen*/
#include <stdio.h>

//Declaring a structure
struct bank_details
 {
  char customer_name[20];
  char cif_no[10];
  int ac_no,pincode;
 };

main()
{
struct bank_details bank;
FILE *file;
file= fopen("bank_file.dat", "w");
printf("Enter A/no:\n");
scanf("%d",&bank.ac_no);
printf("Enter customer name:\n");
scanf("%s",bank.customer_name);
printf("Enter CIF no:\n");
scanf("%s",bank.cif_no);
printf("Enter your PINCODE:\n");
scanf("%d",&bank.pincode);

fwrite(&bank, sizeof(bank), 1, file);
if (file!=0)
{
    printf("Data successfully updated into file\n");
}

fclose(file);
}

Solution

  • This is because you are using fwrite which writes a binary stream of the data you give it. See here. You should use something like fprintf instead:

    fprintf(file, "CustomerName: %s\nCIF Number: %s", bank.customer_name, bank.cif_no);
    

    man fprintf