file i/o writing and reading file in c - c
I am new in c programming.I just start to learn file i/o.So my problem here is after I enter all the data for write file,my program say there is a problem and exited.Which part of my program is wrong?
//THIS PROGRAM WRITE RECORDS IN A TXT.FILE AND THEN READ AND DISPLAY THE RECORDS IN A TXT.FILE
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
struct student
{
char MatricNo[20];
int matric[20];
char CourseNo[20];
int course[20];
char Grade[20];
float Value[20];
}s[10];
int count=0;
int i,j, no,nu;
int write();
int read(int i, int j);
int main()
{
int choice;
printf("To record data to txt type <1>\nTo read data from txt type <2>\nTo end the program type <3>\n\n");
printf("Your Choice: ");
scanf("%i",&choice);
while(choice!=3)
{
switch(choice)
{
case 1:
write();
break;
case 2:
read(i, j);
break;
case 3:
return 0;
break;
default:
break;
}
printf("To record data to txt type <1>\nTo read data from txt type <2>\nTo end the program type <3>\n\n");
printf("Your Choice: ");
scanf("%i",&choice);
}
fflush(stdin);
getchar();
return 0;
}
// for write data to txt file
int write()
{
FILE *fw;
fw=fopen("Register Table.txt","w");
printf("\nEnter number of student :");
scanf("%d",&no);
for(i=0;i<no;i++)
{
printf("\nEnter student MatricNo :");
scanf("%s",&s[i].MatricNo);
printf("\nEnter number of courses :");
scanf("%d",&nu);
for(j=0; j < nu; j++)
{
printf("\nEnter student CourseNo :");
scanf("%s",&s[j].CourseNo);
printf("\nEnter student Grade :");
scanf("%s",&s[j].Grade);
printf("\nEnter student value :");
scanf("%.2f",&s[j].Value);
fflush(stdin);
fprintf(fw,"%5s %5s %5s %.2f\n",s[i].MatricNo,s[j].CourseNo,s[j].Grade,s[j].Value);
fclose(fw);
}
}
}
int read(int i, int j)
{
FILE *fr;
//read data from txt file
fr=fopen("Register Table.txt","r");
if(!fr){
printf("not file");
return 0;
}
else
return 1;
printf("\n\n\t **Register Table **\n");
while(fscanf(fr,"%5s %5s %5s %.2f",&s[i].MatricNo,&s[j].CourseNo,&s[j].Grade,&s[j].Value)==1)
{
//display data from txt file
printf("\n\n MatricNo\t CourseNo\t Grade\t\t Value");
for(i=0;i<no;i++)
{
for(j=0; j < nu; j++)
{
printf("\n\n %5s %5s %5s %.2f",s[i].MatricNo,s[j].CourseNo,s[j].Grade,s[j].Value);
}
}
printf("\n\n");
}
fclose(fr);
}
ok,i edited my program and this is it.But now the problem is after i write the file,it could not be read.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
struct student
{
char MatricNo[20];
int matric[20];
char CourseNo[20];
int course[20];
char Grade[20];
float Value[20];
}s[10];
int count=0;
int i,j, no,nu;
int write();
int read(int no, int nu);
FILE *fw;
int main()
{
int choice;
printf("To record data to txt type <1>\nTo read data from txt type <2>\nTo end the program type <3>\n\n");
printf("Your Choice: ");
scanf("%i",&choice);
while(choice!=3)
{
switch(choice)
{
case 1:
write();
break;
case 2:
read(no, nu);
break;
case 3:
return 0;
break;
default:
break;
}
printf("To record data to txt type <1>\nTo read data from txt type <2>\nTo end the program type <3>\n\n");
printf("Your Choice: ");
scanf("%i", &choice);
}
fflush(stdin);
getchar();
return 0;
}
// for write data to txt file
int write()
{
fw=fopen("Register Table.txt","w");
printf("\nEnter number of student :");
scanf("%d", &no);
for(i=0;i<no;i++)
{
printf("\nEnter student MatricNo :");
scanf("%s", &s[i].MatricNo);
printf("\nEnter number of course :");
scanf("%d", &nu);
for(j=0; j < nu; j++)
{
printf("\nEnter student CourseNo :");
scanf("%s", &s[i].CourseNo[j]);
printf("\nEnter student Grade :");
scanf("%s", &s[i].Grade[j]);
printf("\nEnter student value :");
scanf("%f", &s[i].Value[j]);
}
}
fprintf(fw,"%s %s %s %.2f\n", s[i].MatricNo, s[i].CourseNo[j], s[i].Grade[j], s[i].Value[j]);
fclose(fw);
}
int read(int no, int nu)
{
FILE *fr;
//read data from txt file
fr=fopen("Register Table.txt","r");
printf("\n\n\t **Register Table **\n");
for(i=0;i<no;i++)
{
for(j=0; j < nu; j++)
{
fscanf(fr,"%s %s %s %.2f", &s[i].MatricNo, &s[i].CourseNo[j], &s[i].Grade[j], &s[i].Value[j]);
}
}
//display data from txt file
printf("\n\n MatricNo\t CourseNo\t Grade\t\t Value");
for(i=0;i<no;i++)
{
for(j=0; j < nu; j++)
{
printf("%s %s %s %.2f", s[i].MatricNo, s[i].CourseNo[j], s[i].Grade[j], s[i].Value[j]);
}
}
printf("\n");
fclose(fr);
}
1-you can not write on file because you close the FILE pointer fw in write() function in for loop.
2-You can not read because you exit read() function either file is valid or invalid with this code.
if(!fr){
printf("not file");
return 0;
}
else
return 1;
3- your read() function can work only if you call it after write(). Because code does not know value of no and nu if you do not call write() firstly.
I think this code works for you
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct student
{
char MatricNo[20];
int matric[20];
char CourseNo[20];
int course[20];
char Grade[20];
float Value[20];
}
s[10];
int count=0;
int i,j, no,nu;
int write();
int read(int no, int nu);
FILE *fw;
int main()
{
int choice;
printf("To record data to txt type <1>\nTo read data from txt type <2>\nTo end the program type <3>\n\n");
printf("Your Choice: ");
scanf("%i",&choice);
while(choice!=3)
{
switch(choice)
{
case 1:
write();
break;
case 2:
read(no, nu);
break;
case 3:
return 0;
break;
default:
break;
}
printf("To record data to txt type <1>\nTo read data from txt type <2>\nTo end the program type <3>\n\n");
printf("Your Choice: ");
scanf("%i", &choice);
}
fflush(stdin);
getchar();
return 0;
}
// for write data to txt file
int write()
{
fw=fopen("Register Table.txt","w");
printf("\nEnter number of student :");
scanf("%d", &no);
for(i=0;i<no;i++)
{
printf("\nEnter student MatricNo :");
scanf("%s", &s[i].MatricNo);
printf("\nEnter number of course :");
scanf("%d", &nu);
for(j=0; j < nu; j++)
{
printf("\nEnter student CourseNo :");
scanf("%s", &s[i].CourseNo[j]);
printf("\nEnter student Grade :");
scanf("%s", &s[i].Grade[j]);
printf("\nEnter student value :");
scanf("%f", &s[i].Value[j]);
fprintf(fw,"%s %s %s %.2f\n", &s[i].MatricNo, &s[i].CourseNo[j], &s[i].Grade[j], &s[i].Value[j]);
}
}
fclose(fw);
}
int read(int no, int nu)
{
FILE *fr;
//read data from txt file
fr=fopen("Register Table.txt","r");
printf("\n\n\t **Register Table **\n");
for(i=0;i<no;i++)
{
for(j=0; j < nu; j++)
{
fscanf(fr,"%s %s %s %.2f", &s[i].MatricNo, &s[i].CourseNo[j], &s[i].Grade[j], &s[i].Value[j]);
}
}
//display data from txt file
printf("\n\n MatricNot CourseNot Gradett Value");
for(i=0;i<no;i++)
{
for(j=0; j < nu; j++)
{
printf("\n%s %s %s %.2f", &s[i].MatricNo, &s[i].CourseNo[j], &s[i].Grade[j], &s[i].Value[j]);
}
}
printf("\n");
fclose(fr);
}
Related
I tried to make a find max/min function and it does not work properly while not giving back any errors (C language)
Just as the title said, I tried to make a function that finds max/min grades from a list of grade structs by creating a new variables that stores highest/lowest grades and then compare it with each instance in an array of struct to find the desired result. However, my function does not work as intended and it returns both max grade for both function min and max #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <string.h> struct student{ char name[50], studentID[50]; float grade; } std[30]; int n; void add(){ for (int i=0; i<n; i++){ printf("\nAdd the students details no%d", i+1); printf("\n**********************************"); printf("\nStudent's name: "); scanf(" %s", &std[i].name); getchar(); printf("\nStudent's ID: "); scanf(" %s", &std[i].studentID); getchar(); printf("\nStudent's grade: "); scanf(" %f", &std[i].grade); getchar(); system("cls"); } } void displayRecords(){ for (int i=0; i<n; ++i){ printf("\n**************************"); printf("\nStudent's name: %s", std[i].name); printf("\nStudent's ID: %s", std[i].studentID); printf("\nStudent's grade: %.2f", std[i].grade); printf("\n**************************\n"); } getch(); } float max(){ float maxGrade = std[0].grade; for (int i=0; i<n; i++){ if(std[i].grade > maxGrade); maxGrade = std[i].grade; } printf("Max grade: %.2f", maxGrade); getch(); return maxGrade; } float min(){ float minGrade = std[0].grade; for (int i=0; i<n; i++){ if(std[i].grade < minGrade); minGrade = std[i].grade; } printf("Min grade: %.2f", minGrade); getch(); return minGrade; } int main() { while(1){ int a; system("cls"); printf("\t\t\t\t----------Welcome to SMS----------"); printf("\n\t\t\t\t\tPlease choose your action"); printf("\n\t\t\t\t1.Create new record"); printf("\n\t\t\t\t2.View a record"); printf("\n\t\t\t\t3.Find max grade"); printf("\n\t\t\t\t4.Find min grade"); printf("\n\t\t\t\t5.Exit"); printf("\n\n\n\t\t\t\tYour choice: "); scanf("%d", &a); switch(a){ case 1: system("cls"); printf("Please enter the amount of records you want to add <1-30>: "); scanf("%d", &n); add(n); break; case 2: system("cls"); displayRecords(n); break; case 3: system("cls"); max(n); break; case 4: system("cls"); min(n); break; case 5: system("cls"); printf("\n\t\t\t\t\t\tSee you again next time!"); getch(); return 0; default: system("cls"); printf("Error! Please enter again"); } } }
OP's if() ends too early for min and max. // Bad if(std[i].grade < minGrade); minGrade = std[i].grade; // Should be if(std[i].grade < minGrade) minGrade = std[i].grade; Look carefully. Best to enable all compiler warnings to save you and us time.
How to check if value exists in struct or not?
I want to ask you guys, here my code cannot check is my value is exist or not in struct, I've input the value, but none of them enter the if else condition, can anyone help me? #include <stdio.h> int main(){ int a,i; struct data { char nim[10]; }; struct data batas[100]; printf("TEST1 : "); scanf("%[^\n]s", batas[0].nim); printf("TEST2 : "); scanf(" %[^\n]s", batas[1].nim); printf("TEST3 : "); scanf(" %[^\n]s", batas[3].nim); printf("TEST : "); scanf(" %[^\n]s", batas[a].nim); for(i=0; i<a; i++){ if (batas[a].nim == batas[i].nim) { printf("Value exist"); } else { printf("Value doesn't exist"); } } return 0; }
You can not compare array of chars with the equal operator, instead: if (strcmp(batas[a].nim, batas[i].nim) == 0) or if (!strcmp(batas[a].nim, batas[i].nim)) you need to #include <string.h> Also, note that you are using a uninitialized.
from what you give, it still can't enter the "Value exist" value. Here are my full line of code. #include <stdio.h> #include <string.h> struct data { char nim[10]; }; struct data batas[100]; int a=0, b, c, d; int i, j; char x[20]; void inputdata() { printf("\nInput Data\n"); printf("=======================\n"); printf("NIM : "); scanf("%s", batas[a].nim); for(i=0; i<a; i++){ if (!strcmp(batas[a].nim, batas[i].nim)) { strcpy(x, "FLAG"); } else { strcpy(x, "FLAGX"); } } printf("%s", x); a++; } void showdata() { j=0; for(i=0; i<a; i++){ j = j + 1; printf("\nData-%i", j); printf("\nNIM : %s", batas[i].nim); } } int main() { int menu; do { printf("\nChoose input = "); scanf("%d", &menu); switch(menu) { case 1 : inputdata(); break; case 2 : showdata(); break; } }while (menu != 3); return 0; }
Why am I getting the process error 0xc0000005 with my code in C
This project is the skyline project for a school work, and at the moment I'm getting an error when I'm putting in the coordinates being that this error is 0xc0000005. Everything else is running smoothly as for now if I'm not wrong. If someone could explain to me why this is happening I would be grateful. #include <stdlib.h> typedef struct { int registerednumber; // It registers the number of buildings used in the array of buildings; } registernumber; typedef struct { int li;//POINT MOST TO THE LEFT int hi;//HEIGHT OF THE BUILDING int ri;//POINT MOST TO THE RIGHT } buildings; void exitprogram(){ exit(0); } int menu() { int optioninmenu=0; do { system("cls"); fflush(stdin); printf("-------------SKYLINES------------- \n"); printf(" 1-REGISTER NUMBER OF BUILDINGS \n"); printf(" 2-REGISTER BUILDING COORDINATES \n"); printf(" 3-EXECUTE SKYLINE \n"); printf(" 4-CREDITS \n"); printf(" 5-EXIT \n \n"); printf(" TYPE YOUR OPTION: "); scanf("%d", &optioninmenu); } while(optioninmenu!= 1 && optioninmenu!= 2 && optioninmenu!= 3 && optioninmenu!= 4 && optioninmenu!= 5 && optioninmenu!=0); return(optioninmenu); } int credits() { int returntomenu = 0; system("cls"); printf(" ################################ \n"); printf(" #This program was done by: #\n"); printf(" #Joao Moura A93099 #\n"); printf(" #Eva Castro A93097 # \n"); printf(" ################################ \n \n"); printf("\n TYPE ENTER TO RETURN TO THE MAIN MENU"); getchar(); return menu(); } int countbuildings(buildings *building, int *regnumberofbuildings) { int returntomenu = 0; int i=0; int numberofbuildings=0; system("cls"); printf(" TYPE IN THE NUMBER OF BUILDINGS: "); scanf("%d", &numberofbuildings); *regnumberofbuildings=numberofbuildings; printf("%d",*regnumberofbuildings); printf("\n TYPE ENTER TO RETURN TO THE MAIN MENU"); getchar(); return menu(); } int coordinates(buildings *building,int regnumberofbuildings) { int i=0; building=(buildings *)malloc(regnumberofbuildings*sizeof(building)); system("cls"); printf("%d",regnumberofbuildings); for(i=0;i!=regnumberofbuildings;i++){ system("cls"); printf("Building number %d \n \n", i+1); printf(" TYPE THE LEFTMOST COORDINATE: "); scanf("%d", &building[i].li); printf("\n TYPE IN THE HEIGHT OF THE BUILDING: "); scanf("%d", &building[i].hi); printf("\n TYPE THE RIGHTMOST COORDINATE: "); scanf("%d", &building[i].ri); } printf("\n TYPE ENTER TO RETURN TO THE MAIN MENU"); getchar(); return menu(); } int main() { int numberofbuildings=0; int registerednumber=0; buildings *building; int option=0; int i=0; do{ option=menu(); if(option==1){ countbuildings(building,&numberofbuildings); } if(option==2){ coordinates(building,numberofbuildings); getchar(); } if(option==4){ credits(); } }while(option!=5); if(option==5){ printf("Thanks for using our program!"); printf("Press enter to leave the program"); getchar(); exitprogram(); } return 0; }
I can't seem to run an array for a string variable
I've run this code countless times and I'm not sure what's wrong with it. It won't display the 'subj' variable whenever I run the code and choose the '1. Display' option. All I get is the error 'divide error' 'abnormal program termination '→ ' Here's my code: #include <stdio.h> #include <conio.h> char subj[20], name[20], course[20], studentid[20]; float grade[20], hold, gu[20], guadd, gpa, temp, median, mode, max, a[20]; int z, i, h, n, tu, c, unit[20], count; void disp(int n, int unit[], float grade[], char subj[], char name[], char studentid[], char course[]) { printf("Name: %s\n", name); printf("Course: %s\n", course); printf("Student ID: %s\n", studentid); printf("\n\nSubject\t\t\tUnits\t\t\tFinal Grade\n"); for(i=0; i<n; i++) { printf("%s", subj[i]); printf("\t\t\t%d\t\t\t", unit[i]); printf("\%.2f\n", grade[i]); } tu=0; guadd=0; for(i=0; i<n; i++) { gu[i]=grade[i]*unit[i]; tu+=unit[i]; guadd+=gu[i]; } gpa=guadd/tu; printf("\n\nSemester Grade Point Average:\t\t\t%.2f\n", gpa); } int main() { clrscr(); printf("Enter Student Name: "); scanf ("%s", &name); printf("Enter Student ID: "); scanf ("%s", &studentid); printf("Enter Course: "); scanf ("%s", &course); printf("Please Enter the Amount of Subjects Enrolled: "); scanf ("%d", &n); for(i=0; i<n; i++) { printf("\nPlease Enter the Subject Name: "); scanf("%s", &subj[i]); printf("Please Enter the Final Grade for this Subject: "); scanf ("%f", &grade[i]); printf("Please Enter Number of Units for this Subject: "); scanf ("%d", &unit[i]); } clrscr(); do { printf("\nPlease Choose an Option:\n\n1. Display Grades with GPA\n2. Ascending Order of Grades\n3. Descending Order of Grades\n4. Median and Mode\n5.EXIT\n\nChoice: "); scanf ("%d", &z); clrscr(); switch(z) { case 1: disp(n, unit, grade, subj, name, studentid, course); break; case 2: ascending(n, grade); break; case 3: descending(n, grade); break; case 4: medmod(n, grade); break; } } while (z!=5); getch(); return 0; } P.S. I'm new to this so I don't really know what the issue is. Thanks for the help!
Some changes I made to your code and it works. Replace char subj[20] by char *subj[20] since you need an array of strings, not an array of characters which would be a single string. Then, allocate memory to each of them dynamically (used malloc from C's stdlib.h), say at-least for 100 chars. Also, the gcc compiler generates warnings good enough to know what's going on, so it becomes quite clear to fix your arguments to printf and scanf functions. PS : Since conio.h is non-portable, I removed it and its functions from the code. Modified code : #include <stdio.h> #include <stdlib.h> char *subj[20]; char name[20], course[20], studentid[20]; float grade[20], hold, gu[20], guadd, gpa, temp, median, mode, max, a[20]; int z, i, h, n, tu, c, unit[20], count; void disp(int n, int unit[], float grade[], char *subj[], char name[], char studentid[], char course[]) { printf("Name: %s\n", name); printf("Course: %s\n", course); printf("Student ID: %s\n", studentid); printf("\n\nSubject\t\t\tUnits\t\t\tFinal Grade\n"); for (i = 0; i < n; i++) { printf("%s", subj[i]); printf("\t\t\t%d\t\t\t", unit[i]); printf("\%.2f\n", grade[i]); } tu = 0; guadd = 0; for (i = 0; i < n; i++) { gu[i] = grade[i] * unit[i]; tu += unit[i]; guadd += gu[i]; } gpa = guadd / tu; printf("\n\nSemester Grade Point Average:\t\t\t%.2f\n", gpa); } int main() { for (i = 0; i < 20; i++) subj[i] = malloc(sizeof(char) * 100); printf("Enter Student Name: "); scanf("%s", name); printf("Enter Student ID: "); scanf("%s", studentid); printf("Enter Course: "); scanf("%s", course); printf("Please Enter the Amount of Subjects Enrolled: "); scanf("%d", &n); printf("%s %s %s %d", name, studentid, course, n); for (i = 0; i < n; i++) { printf("\nPlease Enter the Subject Name: "); scanf("%s", subj[i]); printf("%s", subj[i]); printf("Please Enter the Final Grade for this Subject: "); scanf("%f", &grade[i]); printf("Please Enter Number of Units for this Subject: "); scanf("%d", &unit[i]); } do { printf("\nPlease Choose an Option:\n\n1. Display Grades with GPA\n2. " "Ascending Order of Grades\n3. Descending Order of Grades\n4. " "Median and Mode\n5.EXIT\n\nChoice: "); scanf("%d", &z); switch (z) { case 1: disp(n, unit, grade, subj, name, studentid, course); break; case 2: break; case 3: descending(n, grade); break; case 4: medmod(n, grade); break; } } while (z != 5); return 0; }
How can I update an input into an inventory and display it later?
I'm currently having a piece of code here that Im stuck. My problem here is that after I use Add function to add a game into the inventory, I press P to display but it shows that the inventory is empty. So how can I update the new entry into this inventory? #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <ctype.h> #define SIZE 40 typedef struct { char gname[30]; char gcomp[30]; double gprice; } game; void showMenu(char *choice); void gameList(game list[], int num); void HardCodeSix(game list[]); void Add(game list[], int num); int main() { game list[SIZE]; int count = 0; char choice; int num = 0; HardCodeSix(list); count = 6; printf("Welcome to Mini Game-Stop!!\n"); printf("\n"); showMenu(&choice); choice = toupper(choice); printf("Your choice is: %c\n", choice); printf("\n"); while (choice != 'Q') { if (choice == 'P') { gameList(list, num); } else if (choice == 'A') { Add(list, num); } showMenu(&choice); choice = toupper(choice); printf("Your choice is: %c\n", choice); printf("\n"); } printf("Thank for using this program. Bye!\n"); return 0; } void showMenu(char *choice) { printf("** Options: \n"); printf("P....Print list of games.\n"); printf("A....Add more game into the list.\n"); printf("C....Clear all of the choices.\n"); printf("D....Delete one game from the list.\n"); printf("U....Update.\n"); printf("Q....Quit.\n"); printf("\n"); printf("Please enter your choice: "); scanf(" %c", &*choice); } void gameList(game list[], int num) { int i; if (num == 0) { printf("Empty List!\n"); printf("\n"); } for (i = 0; i < num; i++) { printf("Title: %s\n", list[i].gname); printf("Developer: %s\n", list[i].gcomp); printf("Price: $%.2f\n", list[i].gprice); } } void Add(game list[], int num) { printf("Enter game's title: "); scanf("%s", list[num].gname); printf("Enter game's developer: "); scanf("%s", list[num].gcomp); printf("Price: "); scanf("%lf", &list[num].gprice); printf("\n"); }