Question about C language: I am trying to use structures and files i/o in the same code. My goal is to take information

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899603
Joined: Mon Aug 02, 2021 8:13 am

Question about C language: I am trying to use structures and files i/o in the same code. My goal is to take information

Post by answerhappygod »

Question about C language:
I am trying to use structures and files i/o in the same code. Mygoal is to take information from the file "inputfile.txt" and putit into the structure STUDENT and the newly created file"outputfile.txt". With the next code, I am able only to readinformation but it does not appear in the "outputfile.txt" file. Ineed to make the information appear in the outputfile and in theoutput window too. This is the information I am trying to read andinput:
name ID age scholarship schoolstatus abroad address phone cgpa
songju 20091111 20 1 Yes No city district street streetnumber house1 1234567890 3.0heylee 20081234 21 0 Yes No city district street streetnumber house2 2345678901 4.0junia 200500100 25 0 Yes Yes city district street streetnumber house3 3456789012 3.5mike 20102345 20 2 No No city district street streetnumber house4 4567890123 3.3hongil 20081234 22 3 Yes No city district street streetnumber house5 5678901234 4.2
this is the code:
#include <stdio.h>#include <stdlib.h>// struct studentstruct STUDENT{ char name[20]; char address[50]; char schoolstat[10]; char abroad[10]; int phone; int age; int ID; float cgpa;};// Driver programint main (){ FILE *infile, *ofp; struct STUDENT input; infile = fopen ("inputfile.txt", "r"); if (infile == NULL) { fprintf(stderr, "\nError openingfile\n"); exit (1); } ofp=fopen("outputfile.txt", "w"); if(ofp==NULL){ printf("output file openerror!\n"); return 1; } int res; while(fread(&input, sizeof(struct STUDENT), 1,infile)){ res = printf ("%d %s %s %s %d %f %d%s\n", input.ID, input.name, input.address,input.abroad, input.age, input.cgpa, input.phone,input.schoolstat); if(res==EOF) break; fprintf(ofp, "%d %s %s %s %d%f %d %s\n", input.ID, input.name, input.address,input.abroad, input.age, input.cgpa, input.phone,input.schoolstat); } // close file fclose (infile); return 0;}
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply