समस्या
एक फ़ाइल में 5 छात्रों के विवरण संग्रहीत करने के लिए एक C प्रोग्राम लिखें और इसे fread() और fwrite()
का उपयोग करके प्रिंट करें।समाधान
फ़्रेड () फ़ंक्शन एक बार में पूरा रिकॉर्ड पढ़ता है।
वाक्यविन्यास
fread( & structure variable, size of (structure variable), no of records, file pointer);
उदाहरण
struct emp{ int eno; char ename [30]; float sal; } e; FILE *fp; fread (&e, sizeof (e), 1, fp);
फराइट () फ़ंक्शन एक बार में पूरा रिकॉर्ड लिखता है।
वाक्यविन्यास
fwrite( & structure variable , size of structure variable, no of records, file pointer);
उदाहरण
struct emp{ int eno: char ename [30]; float sal; } e; FILE *fp; fwrite (&e, sizeof(e), 1, fp);
कार्यक्रम
#include<stdio.h> struct student{ int sno; char sname [30]; float marks; char temp; }; main ( ){ struct student s[60]; int i; FILE *fp; fp = fopen ("student1.txt", "w"); for (i=0; i<2; i++){ printf ("enter details of student %d\n", i+1); printf("student number:"); scanf("%d",&s[i].sno); scanf("%c",&s[i].temp); printf("student name:"); gets(s[i].sname); printf("student marks:"); scanf("%f",&s[i].marks); fwrite(&s[i], sizeof(s[i]),1,fp); } fclose (fp); fp = fopen ("student1.txt", "r"); for (i=0; i<2; i++){ printf ("details of student %d are\n", i+1); fread (&s[i], sizeof (s[i]) ,1,fp); printf("student number = %d\n", s[i]. sno); printf("student name = %s\n", s[i]. sname); printf("marks = %f\n", s[i]. marks); } fclose(fp); getch( ); }
आउटपुट
enter details of student 1 student number:1 student name:pinky student marks:56 enter details of student 2 student number:2 student name:rosy student marks:87 details of student 1 are student number = 1 student name = pinky marks = 56.000000 details of student 2 are student number = 2 student name = rosy marks = 87.000000