C examples for File:Text File
Write Structures to a Text File using the function fprintf()
#include <stdio.h> struct biodata{ char name[15]; int rollno; int age; float weight; };//from ww w .j a v a 2s. co m int main() { int k = 0; char flag = 'y'; FILE *fptr; struct biodata sa; fptr = fopen("C:\\Code\\data.dat", "w"); if (fptr != NULL) { printf("File is opened successfully.\n"); while(flag == 'y'){ printf("Enter name, roll no, age, and weight of agent: "); scanf("%s %d %d %f", sa.name, &sa.rollno, &sa.age, &sa.weight); fprintf(fptr, "%s %d %d %.1f", sa.name,sa.rollno,sa.age,sa.weight); fflush(stdin); printf("Any more records(y/n): "); scanf(" %c", &flag); } k = fclose(fptr); if(k == -1) puts("File-closing failed"); if(k == 0) puts("File is closed successfully."); } else puts("File-opening failed"); return(0); }