i am trying to sort an array of structures and put it in a file
here is the code
when i open the file which is written in it, a garbage is found in the file
would anyone tell me what is the problem of this
here is the code
Code:
#include <stdio.h> #include<string.h> struct Contacts { char name[20]; int phone; char address[20]; }; int countLines(FILE * fp); void readfromfile(int c); int main(int argc, char** argv) { FILE *f=fopen("D:\\test.txt","r"); int c; c=countLines(f); printf("number of lines %d \n \n ",c); readfromfile(c); return 0; } int countLines(FILE * fp){ char line[80]; int counter = 0; while ( fgets(line, sizeof line, fp) ){ counter+=1; } return counter; } void readfromfile(int c) { int i,j; struct Contacts array[c]; FILE *f=fopen("D:\\test.txt","rw"); struct Contacts temp; for(i=0;i<c;i++) { fscanf(f,"%s %d %s",array[i].name,&array[i].phone,array[i].address); printf("%s %d %s \n \n ",array[i].name,array[i].phone,array[i].address); } for(i=0;i<c;i++) { for(j=1;j<c;j++) { if(strcmp(array[i].name,array[j].name) > 0 ) { temp=array[i]; array[i]=array[j]; array[j]=temp; } } } fclose(f); FILE* fp = fopen("D:\\test.txt", "a"); for(i=0;i<c;i++) { fprintf(f,"%s %d %s",array[i].name,&array[i].phone,array[i].address); } fclose(fp); }
would anyone tell me what is the problem of this
Comment