Reading and appending a file in C -
i new c , wrote code collects student data, facing few problems.it's not reading file, secondly, when try append, new data not being added new line. doing wrong?
#include <stdio.h> #include<stdlib.h> #include<string.h> int givechoiceforfileopentype(); void writefile(); void readfile(); void apendfile(); void printchoices(); int openfilefromconsole(file *fp1); void savestudentgradeinfotofile(file *fp1); typedef struct student { char name[50]; char id [20]; int score; }student; int main() { printchoices(); int choice = givechoiceforfileopentype(); switch(choice){ case 1: writefile(); break; case 2: readfile(); break; case 3: apendfile(); break; default: printf("error!!!\n"); } return 0; } void writefile(){ file *fp1 =fopen("e://registry.csv", "w"); openfilefromconsole(fp1); savestudentgradeinfotofile(fp1); fclose(fp1); } void readfile(){ file *fp2 = fopen("e://registry.csv", "r"); openfilefromconsole(fp2); fclose(fp2); } void apendfile(){ file *fp3 = fopen("e://registry.csv", "a"); openfilefromconsole(fp3); savestudentgradeinfotofile(fp3); fclose(fp3); } void printchoices(){ printf("1.write\n"); printf("2.read\n"); printf("3.append\n"); return; } int givechoiceforfileopentype(){ int choice; printf("select fileopen type:"); scanf("%d",&choice); return choice; } int openfilefromconsole(file *fp1){ if(fp1 == null ) { printf("error!"); return 0; } return 1 ; } void readingdatafromfile(){ } void savestudentgradeinfotofile(file *fp1) { int numofstudent ; student s[100]; printf ("get number of students :"); scanf("%d",&numofstudent); for(int = 0; < numofstudent; i++) { printf("\nenter id number:"); scanf(" %s",s[i].id); printf("enter name: "); scanf("%s,",s[i].name); printf("enter score: "); scanf("%d",&s[i].score); fprintf(fp1,"%s, %s, %d",s[i].id,s[i].name,s[i].score); printf("\n"); } }
if want put output onto separate lines, need add in \n
character in format string this
fprintf(fp1,"%s, %s, %d\n",s[i].id,s[i].name,s[i].score);
Comments
Post a Comment