I created a small program to input some records to a file.
#include<stdio.h>
int main(void)
{
FILE *fp;
//opening a file to write
fp = fopen("try.rec","w");
if(fp == NULL)
{
printf("\nSorry! Couldn't Create File");
exit(-1);
}
int id = 1;
char name[300] = "Cipher", address[300] = "Virtual Street", phone[20] = "223322212";
fprintf(fp,"%d, %s, %s, %s", id, name, address, phone);
fclose(fp);
return 0;
}
Now, it does good work there is not error in this. But i also made a small program to read that record:
#include<stdio.h>
int main(void)
{
FILE *fp;
fp = fopen("try.rec","r");
if (fp == NULL)
{
printf("Could not Access File. :(");
return -1;
}
int id;
char name[300], add[300], phone[20];
fscanf(fp, "%d , %s , %s , %s",&id, &name, &add, &phone);
fclose(fp);
printf("\nDetails from File try.rec\n---------------------------\nID: %d \nName: %s \nAddress: %s \nPhone: %s \n", id, name, add, phone);
return 0;
}
But when printing the third string it prints garbage values. I dug deeper and found out that when i replace "Cipher"
with "Cipher "
(having one extra space at last) in my first program and run it, then the third string in second program outputs only Virtual
(and nothing after space) and then the fourth string is garbage again.
So, is there any other good alternative ways to put and get the string from file in C. Or Am I doing wrong thing in either of my program?
Anticipating Your Help!
Thanks in Advance.