I created a small program for entering some records into 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 he is doing a good job, and there is no mistake. But I also made a small program to read this entry:
#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 line, it prints garbage values. I went deeper and found out that when I replace "Cipher" with "Cipher " (with one extra space) in my first program and run it, then the third line in the second program displays only Virtual (and nothing after the space), and then the fourth string is garbage again.
So, are there any other good alternative ways to put and get a line from a file in C. Or am I doing the wrong thing in any of my programs?
Foreboding for your help!
Thanks at Advance.