I have a code where I am able to add my struct array to a file, but am unable to continue adding contacts to my struct array like I should.
Here are my variables:
struct contact { // Data structure that holds contact information
char FirstName[10]; // Array for first name
char LastName[10]; // Array for last name
int PhoneNum; // Phone number
};
int Choice = 0;
int n = 0;
int size = 1;
struct contact *con = (struct contact *)malloc(size * sizeof(struct contact));
int a = 0;
int b = 0;
int SortChoice = 0;
int iRandNum = 0;
int Valid = 0;
char temp[10];
int tempNum = 0;
char File[20];
int status = 0;
FILE *pRead;
FILE *pWrite;
Here is the add contact part:
if (n == size)
{
size = size * 2;
con = (struct contact*)realloc(con, size * sizeof(struct contact));
}
// Records the information given into the structure
printf("\nYou chose to add a contact.");
printf("\nFirst name: ");
scanf("%s", con[n].FirstName);
printf("\nLast name: ");
scanf("%s", con[n].LastName);
printf("\nPhone number (Numbers only): ");
scanf("%d", &con[n].PhoneNum);
printf("\nRecord added to the phone book.");
// Prints out the given information
printf("\n\nNew contact:");
printf("\nFirst name: %s", con[n].FirstName);
printf("\nLast name: %s", con[n].LastName);
printf("\nPhone number: %d", con[n].PhoneNum);
printf("\nContact number is %d", n);
printf("\n");
n += 1;
And here is the file part:
printf("\nYou chose to store all contacts to a file.");
if (status == 0){
printf("\nWhat would you like to name your file?\n");
scanf("%s", &File);
printf("\nFile name is %s", File);
pWrite = fopen(File, "w");
if (pWrite == 0){
printf("\nFile not opened");
}
else {
for (a = 0; a < n; a++){
fwrite(&con[a], sizeof(struct contact), 1, pWrite);
}
fclose(pWrite);
pRead =fopen(File, "r");
printf("\n\nContacts added to %s", File);
printf("\n\nContacts in file:\n");
while (fread(&con[a], sizeof(struct contact),1, pRead)){
printf("\n");
printf("\nFirst name: %s", con[a].FirstName);
printf("\nLast name: %s", con[a].LastName);
printf("\nPhone number: %d", con[a].PhoneNum);
printf("\n");
}
fclose(pRead);
}
}
If you guys can figure out where I've gone wrong, and potentially why I can't continue to access the file I created that would be great. Thanks
Related
I need to solve a problem. I need to create two functions which scan user's input information and put in into structure array and then put all array to BIN file (with function fwrite()) and other function - read from BIN file with function fread(). You can see my code below. Problem is that I can write to file, but when I read I get filler array element and other element which are empty. How to get only filled struct array element?
#include <stdio.h>
#include <stdlib.h>
#include <mem.h>
typedef struct
{
char Lesson[50];
char TeachersName[50];
char TeachersLastName[50];
int Credits;
int NumberOfStudents;
} School;
void ToFile (char *fileName);
void FromFile (char *FileName);
int main()
{
char *fileName[]={"student.bin"};
ToFile (*fileName);
FromFile (*fileName);
return 0;
}
void ToFile (char *fileName)
{
int n, chars;
FILE *fp;
fp = fopen(fileName, "wb");
School Info[20];
if(fp == NULL)
{
printf("Error opening file\n");
exit(1);
}
printf("Testing fwrite() function: \n\n");
printf("Enter the number of records you want to enter: ");
scanf("%d", &n);
for(int i = 0;i<n;i++)
{
printf("\nEnter details of employee %d \n", i + 1);
fflush(stdin);
printf("Lesson: ");
gets(Info[i].Lesson);
printf("Teachers name: ");
gets(Info[i].TeachersName);
printf("Teachers last name: ");
gets(Info[i].TeachersLastName);
printf("Credits: ");
scanf("%d", &Info[i].Credits);
printf("Number of studens: ");
scanf("%d", &Info[i].NumberOfStudents);
chars = fwrite(&Info[i], sizeof(Info), 1, fp);
printf("Number of items written to the file: %d\n", chars);
}
fclose(fp);
}
void FromFile (char *FileName)
{
School Info[20]= { { "", "","",0,0 } };;
FILE * fpp;
fpp = fopen(FileName, "rb");
fread(&Info, sizeof(Info), 1, fpp);
/*
for(int j=0; j<20; ++j) {
printf("\nLesson: %s", Info[j].Lesson);
printf("\nTeachers name: %s", Info[j].TeachersName);
printf("\nTeachers last name: %s", Info[j].TeachersLastName);
printf("\nCredits: %d", Info[j].Credits);
printf("\nNumber of students: %d", Info[j].NumberOfStudents);
printf("\n");
}*/
int j=0;
while (fread(&Info, sizeof(Info), 1, fpp))
{
printf("\nLesson: %s", Info[j].Lesson);
printf("\nTeachers name: %s", Info[j].TeachersName);
printf("\nTeachers last name: %s", Info[j].TeachersLastName);
printf("\nCredits: %d", Info[j].Credits);
printf("\nNumber of students: %d", Info[j].NumberOfStudents);
printf("\n");
j++;
}
fclose(fpp);
}
I am trying to make this simple hospital management system for my school project in C, when i try to edit the existing patient details by searching with their id number, That patient information gets edited, patient id,name etc but the problem is all other patients information that i don't want to edit becomes blank(means in place of id it becomes 0 and other remains blank except the edited patients details).
How do i edit only the details of patient i want to edit??
My code for editing
fp is my original filename and temp is temporary file i have created
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<process.h>
typedef struct Hospital{
int patientId;
char fname[20];
char lname[20];
char gender[10];
int age;
char ReferredTo[30];
}Hospital;
Hospital hospi;
void Record();
void Display();
void Add();
void Edit();
void Search();
void Delete();
int main(){
int ch;
top:
printf("\n1.Create Record of patients");
printf("\n2.Display Record of patients");
printf("\n3.Append Record of Additional patients");
printf("\n4.Edit the record of the patients");
printf("\n5.Search record of the patients");
printf("\n6.Delete record of the patients");
printf("\n---------------------------------------");
printf("\nEnter your choice: ");
scanf("%d",&ch);
printf("\n---------------------------------------");
if(ch == 1){
Record();
}else if(ch == 2){
Display();
} else if(ch == 3){
Add();
//goto top;
}else if(ch == 4){
Edit();
}else if(ch == 5){
Search();
}else if(ch == 6){
Delete();
}else{
printf("Invalid Choice");
}
}
void Record(){
FILE *fp;
int n = 0,i;
fp = fopen("C:\\project\\record.txt","w");
if(fp == NULL){
printf("Couldn't Open the file");
}else{
printf("\nHow many Record You want to enter: ");
scanf("%d",&n);
for(i=0; i<n; i++){
printf("\nEnter Patient ID: ");
scanf("%d",&hospi.patientId);
printf("\nEnter Patient First Name: ");
scanf("%s",hospi.fname);
fflush(stdin);
printf("\nEnter Patient Last Name: ");
scanf("%s",hospi.lname);
printf("\nEnter Patient sex(M for male F for Female): ");
scanf("%s",hospi.gender);
printf("\nEnter Patient Age: ");
scanf("%d",&hospi.age);
printf("\nEnter the Doctor Name which the patients is refered to: ");
scanf("%s",hospi.ReferredTo);
fwrite(&hospi,sizeof(hospi),1,fp);
}
printf("\nData Successfully Recorded....:)");
}
fclose(fp);
}
void Display(){
FILE *fp;
fp = fopen("C:\\project\\record.txt","r");
if(fp == NULL){
printf("Error: can't open file");
}else{
while(fread(&hospi,sizeof(hospi),1,fp)==1){
printf("\nPatient Id = %d\n",hospi.patientId);
printf("Patient Fullname = %s %s\n",hospi.fname,hospi.lname);
fflush(stdin);
printf("Patient Gender: %s\n",hospi.gender);
printf("Patient Age = %d\n",hospi.age);
printf("Referred Doctorr = %s\n",hospi.ReferredTo);
printf("---------------------------------------\n");
}
}
fclose(fp);
}
void Add(){
FILE *fp;
char ch;
int n = 0,i;
fp = fopen("C:\\project\\record.txt","a");
if(fp == NULL){
printf("Error: can't open file");
}else{
//printf("\nHow many Additional patients you want to add: ");
//scanf("%d",&n);
printf("\nEnter Patient ID: ");
scanf("%d",&hospi.patientId);
printf("\nEnter Patient First Name: ");
scanf("%s",hospi.fname);
fflush(stdin);
printf("\nEnter Patient Last Name: ");
scanf("%s",hospi.lname);
printf("\nEnter Patient sex(M for male F for Female): ");
scanf("%s",hospi.gender);
printf("\nEnter Patient Age: ");
scanf("%d",&hospi.age);
printf("\nEnter the Doctor Name which the patients is refered to: ");
scanf("%s",hospi.ReferredTo);
fwrite(&hospi,sizeof(hospi),1,fp);
}
printf("\nDo you want to continue adding data press('y' for yes and 'N' for no ) ");
scanf("%s",ch);
while(ch =='y'){
Add();
}
fclose(fp);
}
void Edit(){
int Pid;
FILE *fp,*temp;
fp = fopen("C:\\project\\record.txt","r");
temp = fopen("C:\\project\\temp.txt","a");
Hospital hospt;
printf("\nEnter the patient ID you want to Edit the data: ");
scanf("%d",&Pid);
while(fread(&hospt,sizeof(hospt),1,fp)==1){
if(Pid == hospt.patientId){
printf("\nEnter Patient ID: ");
scanf("%d",&hospi.patientId);
printf("\nEnter Patient First Name: ");
scanf("%s",hospi.fname);
fflush(stdin);
printf("\nEnter Patient Last Name: ");
scanf("%s",hospi.lname);
printf("\nEnter Patient sex(M for male F for Female): ");
scanf("%s",hospi.gender);
printf("\nEnter Patient Age: ");
scanf("%d",&hospi.age);
printf("\nEnter the Doctor Name which the patients is refered to: ");
scanf("%s",hospi.ReferredTo);
fwrite(&hospi,sizeof(hospi),1,temp);
}else{
fwrite(&hospi,sizeof(hospi),1,temp);
}
}
fclose(fp);
fclose(temp);
remove("C:\\project\\record.txt");
rename("C:\\project\\temp.txt","C:\\project\\record.txt");
}
void Search(){
FILE *fp;
int found_name = 0;
char search_name[20];
printf("\nEnter the Patient name you want to search for: ");
scanf("%s",search_name);
fp = fopen("C:\\project\\record.txt","r");
while(fread(&hospi,sizeof(hospi),1,fp)==1){
if(strcmp(search_name,hospi.fname)==0){
found_name++;
printf("\nPatient Id = %d\n",hospi.patientId);
printf("Patient Fullname = %s %s\n",hospi.fname,hospi.lname);
fflush(stdin);
printf("Patient Gender: %s\n",hospi.gender);
printf("Patient Age = %d\n",hospi.age);
printf("Referred Doctorr = %s\n",hospi.ReferredTo);
break;
}
}
if(found_name==0){
printf("\nThe Patient Name you searched for is not register in our system...:(");
}
fclose(fp);
}
void Delete(){
FILE *fp,*temp;
Hospital hospt;
int delete_id,found = 0;
fp = fopen("C:\\project\\record.txt","r");
temp = fopen("C:\\project\\temp.txt","a");
printf("\nEnter the patient id you want to Delete: ");
scanf("%d",&delete_id);
while(fread(&hospt,sizeof(hospt),1,fp)==1){
if(delete_id != hospt.patientId){
fwrite((&hospt),sizeof(hospt),1,temp);
}else{
found++;
}
}
fclose(fp);
fclose(temp);
remove("C:\\project\\record.txt");
rename("C:\\project\\temp.txt","C:\\project\\record.txt");
if(found>0)
{
printf("Data found and delete successfully\n");
}else{
printf("The Patiend id you want to delete is not in the File");
}
}
You're writing hospi whether you update it or not; both if part and else part. You may want to write hospi when matching input, hospt otherwise.
while (fread(&hospt, sizeof(hospt), 1, fp) == 1) {
// ^^^^^
if (Pid == hospt.patientId) {
// ^^^^^
printf("\nEnter Patient ID: ");
scanf("%d", &hospi.patientId);
// ^^^^^
/* ... */
fwrite(&hospi, sizeof(hospi), 1, temp);
// ^^^^^
} else {
fwrite(&hospi, sizeof(hospi), 1, temp);
// ^^^^^
}
}
In the code below I'm trying to insert, display and delete data from a file.txt. I'm being able to insert successfully but my display function do not display correct and I don't know how to set up the logic to make the delete function. I would appreciate some help in changing the code so it can works. How can I set up the logic for it?
#include <stdio.h>
void menu() {
printf("Option 1 - Create a file and insert data:\n");
printf("Option 2 - Read file and display:\n");
printf("Option 3 - Delete content:\n");
printf("Option 4 - Exit:\n");
};
struct Book {
char title[256];
char author[256];
int pages;
int price;
};
void get() {
struct Book *book;
book = (struct Book*)malloc(sizeof(struct Book));
FILE *fPtr;
fPtr = fopen("file.txt", "w");
if (fPtr == NULL) {
printf("Fail creating file");
getch();
exit(1);
};
for (int i = 0; i < 1; i++) {
printf("Enter the book title:\n");
scanf("%s", &book[i].title);
fprintf(fPtr, "Title = %s", book[i].title);
printf("Enter the author of the book:\n");
scanf("%s", &book[i].author);
fprintf(fPtr, "Author = %s", book[i].author);
printf("Enter the number of pages:\n");
scanf("%d", &book[i].pages);
fprintf(fPtr, "Pages = %d", book[i].pages);
printf("Enter the price:\n");
scanf("%d", &book[i].price);
fprintf(fPtr, "Price = %d", book[i].price);
};
/*for (int i = 0; i < 1; i++) {
printf("%s\n", book[i].title);
printf("%s\n", book[i].author);
printf("%d\n", book[i].pages);
printf("%d\n", book[i].price);
};*/
fclose(fPtr);
};
void display() {
FILE *fPtr;
fPtr = fopen("file.txt", "r");
printf("The content of file are:\n", fPtr);
/*struct Book *book;
book = (struct Book*)malloc(sizeof(struct Book));
printf("%s %s %d %d", book.title, book.author, book.pages, book.price);*/
free(book);
fclose(fPtr);
}
int main()
{
int opt = 0;
int opt2 = 0;
int var = 0;
int validation = 0;
while (opt != 4) {
menu();
do
{
printf("Choose an option:\n");
validation = scanf_s("%d", &opt);
while (getchar() != '\n');
} while (validation != 1);
switch (opt) {
case 1:
get();
printf("Option 5 - Display data:\n");
printf("Option 6 - Delete:\n");
scanf("%d", &var);
if (var == 5) {
//FILE *fp1;
/*fp1 = fopen("file.txt", "r");*/
display();
}
else if (var == 6) {
printf("delete!");
}
break;
case 2:
printf("First insert data:\n");
break;
case 3:
printf("First insert data:\n");
break;
case 4:
return 0;
}
}
}
note : display() proposal 2
void display() {
FILE *fp;
fp = fopen("file.txt", "r");
struct Book book;
printf("%s %s %d %d", book.title, book.author, book.pages, book.price);
free(book);
fclose(fp);
}
I encourage you to rename Books to Book because that struct manages one book, not several.
About the command codes to enter, rather than 1 .. 4 what about 'c' for create, 'r' for read, 'd' for delete and 'e' for exit ?
Concerning get() :
you have a memory leak because the allocated Books is not freed. This allocation is useless, better to have struct Book book;
for (int i = 0; i < 1; i++) is useless and equivalent to int i = 0, do you really manages only 1 book ?
in your fprintf move the '\n' from the beginning to the end, else your file starts by an empty line and the last line is not ended
Is it necessary to prefix each data by its kind like Title = ? To read the file content is more complex with these prefixes
Concerning display() :
you do not read the content of the file, so difficult do display it :)
you allocate a Books, do not initialize it, but write its( uninitialized) fields
for (int i = 0; i < 1; i++) is useless and equivalent to int i = 0
you have a memory leak because the allocated Books is not freed. This allocation is useless, better to have struct Book book;
Concerning display() :
you do not read the content of the file, so difficult do display it :)
you allocate a Books, do not initialize it, but write its( uninitialized) fields
for (int i = 0; i < 1; i++) is useless and equivalent to int i = 0
you have a memory leak because the allocated Books is not freed. This allocation is useless, better to have struct Book book;
Concerning deleteStudentRecord() :
getNoOfRecords() is not defined, but currently it must return 1 because you manage only one book in the file
var is not defined, nor ptr
open file2 with "w", it is a new file
fread(&var, sizeof(struct student), 1, ptr) is wrong because it supposes a line has always sizeof(struct student) but this is not the case refering to get()
fcloseall() ??? just do fclose(ptr); and fclose(ptr2), rename them fpIn and fpOut or something like will make your code more readable
"get(); proposal 2"
void get() {
FILE *fPtr;
fPtr = fopen("file.txt", "w");
struct Book book;
if (fPtr == NULL) {
printf("Fail creating file");
getch();
exit(1);
};
printf("Enter the book title:\n");
scanf("%s", &book.title);
fprintf(fPtr, "%s", book.title);
printf("Enter the author of the book:\n");
scanf("%s", &book.author);
fprintf(fPtr, "%s", book.author);
printf("Enter the number of pages:\n");
scanf("%d", &book.pages);
fprintf(fPtr, "%d", book.pages);
printf("Enter the price:\n");
scanf("%d", &book.price);
fprintf(fPtr, "%d", book.price);
/*for (int i = 0; i < 1; i++) {
printf("%s\n", book[i].title);
printf("%s\n", book[i].author);
printf("%d\n", book[i].pages);
printf("%d\n", book[i].price);
};*/
fclose(fPtr);
};
My program is to ask the user to enter the name and age of the person in his group. The number of person is not known to the user in the beginning of the program. The user keeps on entering the data till the user enters the age zero. The program finally prints the average age.
The source code is below
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
typedef struct group {
char user_Name[21];
int user_age;
}Group;
int main()
{
Group *REC1;
FILE *out_file, *read_file;
int count_age=0, age, sum_age, i;
float avg_age;
char name[21]="", str[21]= "details.txt";
char sample_chr;
//opening a file in writing mode
out_file = fopen(str, "a");
// test for files not existing.
if (out_file == NULL)
{
printf("Error! Could not open file\n");
exit(-1); // must include stdlib.h
}
printf("\nEnter the Details of the person:\n\n");
do
{
printf("Enter the User Name:\n");
fflush(stdin);
scanf("%[^\n]",name);
printf("Enter the Age:\n");
fflush(stdin);
scanf("%d",&age);
if(age == 0)
{
break;
}
else
{
// write to file
fprintf(out_file,"%s,%d\n", name, age);
}
}while(1);
read_file = fopen(str,"r");
//counting the number of lines present in the above file
sample_chr = getc(read_file);
while (sample_chr != EOF)
{
if (sample_chr == '\n')
count_age = count_age +1;
sample_chr = getc(read_file);
}
rewind(read_file);
//allocating space for array of structure dynamically
printf("\n%d\n",count_age);
count_age = count_age - 1;
REC1 = (Group*)malloc(count_age*sizeof(Group));
//storing the values in array of structures
for(i=0; i<=count_age; i++)
fscanf(read_file, "%s,%d", REC1[i].user_Name, &REC1[i].user_age);
fclose(read_file);
fclose(out_file);
for(i =0; i<=count_age; i++)
printf("\n%s %d\n", REC1[i].user_Name, REC1[i].user_age);
for(i=0, sum_age=0; i<=count_age; i++)
sum_age = sum_age + REC1[i].user_age;
avg_age = (float)sum_age/(count_age);
printf("\n\nThe average age is %f\n\n\n", avg_age);
system("pause");
return 0;
}
while i am compiling it doesn't shows any error. When i am running it shows exe file stopped working.
the following is working
there had to be changed the format in scanf() of name[] ( http://www.cplusplus.com/reference/cstdio/scanf/ )
, the fclose(out_file) had to be moved and the ending condition of the while loop had to be changed ...
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
typedef struct group {
char user_Name[21];
int user_age;
}Group;
int main()
{
Group *REC1;
FILE *out_file, *read_file;
int count_age=0, age, sum_age, i;
float avg_age;
char name[21]="", str[21]= "details.txt";
char sample_chr;
//opening a file in writing mode
out_file = fopen(str, "w");
// test for files not existing.
if (out_file == NULL)
{
printf("Error! Could not open file\n");
exit(-1); // must include stdlib.h
}
printf("\nEnter the Details of the person:\n\n");
do
{
printf("Enter the User Name:\n");
scanf("%21s[^\n]",name);
printf("Enter the Age:\n");
scanf("%d",&age);
if(age == 0)
{
break;
}
else
{
// write to file
fprintf(out_file,"%s , %d \n", name, age);
}
}while(age != 0);
fclose(out_file);
read_file = fopen(str,"r");
//counting the number of lines present in the above file
sample_chr = getc(read_file);
while (sample_chr != EOF)
{
if (sample_chr == '\n')
count_age = count_age +1;
sample_chr = getc(read_file);
}
rewind(read_file);
//allocating space for array of structure dynamically
printf("\n Number of group members : %d \n",count_age);
count_age = count_age - 1;
REC1 = (Group*)malloc(count_age*sizeof(Group));
//storing the values in array of structures
for(i=0; i<=count_age; i++)
fscanf(read_file, "%s , %d", REC1[i].user_Name, &REC1[i].user_age);
fclose(read_file);
for(i =0; i<=count_age; i++)
printf("\n Name : %s Age : %d \n", REC1[i].user_Name, REC1[i].user_age);
for(i=0, sum_age=0; i<=count_age; i++)
sum_age = sum_age + REC1[i].user_age;
avg_age = (float)sum_age/(count_age);
printf("\n\nThe average age is %f\n\n\n", avg_age);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SLENG 50 //just a random value
typedef struct Song
{
char *name;
char *nameSong;
char *timeSong;
int date;
} Song;
void saveToFile(Song *x, int *songCount) //Saves info to the binary file
{
FILE *f = fopen("array.txt", "w");
if (f == NULL)
{
printf("Error\n");
}
fwrite(songCount, sizeof(int), 1, f);
fwrite(x, sizeof(struct Song), (*songCount), f);
fclose(f);
}
void readSong(Song *x, int *songCount) //Reads info fromt he file and writes it
{
FILE *fr = fopen("array.txt", "r");
if (fr == NULL)
{
printf("Error\n");
}
printf("Songs:\n");
fread(songCount, sizeof(int), 1, fr);
fread(x, sizeof(struct Song), (*songCount), fr);
for(int i=0; i < (*songCount); i++)
{
printf("%d. %s %s %s %d\n", (i+1), x[i].name, x[i].nameSong, x[i].timeSong, x[i].date);
}
fclose(fr);
}
void insertSong(Song *x, int Count) //Inserts new song into the array.
{
printf("\nInsert name of the band:\n");
x[Count].name=malloc(SLENG * sizeof(char));
scanf("%s", x[Count].name);
printf("Insert name of the song:\n");
x[Count].nameSong=malloc(SLENG * sizeof(char));
scanf("%s", x[Count].nameSong);
printf("Insert length of the song:\n");
x[Count].timeSong=malloc(SLENG * sizeof(char));
scanf("%s", x[Count].timeSong);
printf("Insert then song was created:\n");
scanf("%d", &(x[Count].date));
printf("\n");
}
main()
{
int songCount, menuOption;
Song *x=malloc(SLENG*sizeof(char)+SLENG*sizeof(char)+SLENG*sizeof(char)+sizeof(int));
printf("1. insert song\n 2. load from file\n ");
scanf("%d", &menuOption);
switch(menuOption)
{
case(1) :
printf("Insert how many songs do you want to input?\n");
scanf("%d", &songCount);
for(int i=0; i<songCount; i++)
{
insertSong(x, i);
}
saveToFile(x, &songCount);
break;
case(2) :
readSong(x, &songCount);
break;
}
}
I have an assingment to write a programm which would input some data into file and could read that data from that file, the problem is probably with fwrite or fread, couse it seems to crash everytime I try to load the and write the data from file. Any ideas why is it not working properly? And can I even do it like this as it is dynamic struct array. Thanks in advance.
In order to save the structure to a file, it must only contain scalar values, not pointers into memory objects. Modify your structure to use arrays instead of pointers:
typedef struct Song {
char name[SLENG];
char nameSong[SLENG];
char timeSong[SLENG];
int date;
} Song;
And modify the code accordingly, but note that:
saving and reading the structures to and from a file requires opening it in binary mode "wb" and "rb".
it is very misleading to name a binary file array.txt.
you do not need to pass the address of the count when writing to the file, but you need to pass the address of the array pointer when reading as you do not know yet how much memory to allocate.
Here is the modified code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SLENG 50 // this value is used in the file format
typedef struct Song {
char name[SLENG];
char nameSong[SLENG];
char timeSong[SLENG];
int date;
} Song;
int saveToFile(Song *x, int songCount) { //Saves info to the binary file
FILE *f = fopen("array.bin", "wb");
if (f == NULL) {
printf("Error\n");
return -1;
}
fwrite(songCount, sizeof(int), 1, f);
int written = fwrite(x, sizeof(struct Song), songCount, f);
fclose(f);
return written;
}
int readSong(Song **x, int *songCount) { //Reads info from the file and writes it
int count = 0;
FILE *fr = fopen("array.bin", "rb");
if (fr == NULL) {
printf("Error\n");
return -1;
}
printf("Songs:\n");
fread(&count, sizeof(int), 1, fr);
*x = calloc(count, sizeof(Song));
if (*x == NULL) {
printf("Cannot allocate %d bytes of memory\n", count);
fclose(fr);
return -1;
}
int found = fread(*x, sizeof(struct Song), count, fr);
for (int i = 0; i < found; i++) {
printf("%d. %s %s %s %d\n", i + 1,
(*x)[i].name, (*x)[i].nameSong, (*x)[i].timeSong, (*x)[i].date);
}
fclose(fr);
return *songCount = found;
}
void insertSong(Song *x, int Count) { //Inserts new song into the array.
printf("\nInsert name of the band:\n");
scanf("%49s", x[Count].name);
printf("Insert name of the song:\n");
scanf("%49s", x[Count].nameSong);
printf("Insert length of the song:\n");
scanf("%49s", x[Count].timeSong);
printf("Insert then song was created:\n");
scanf("%d", &(x[Count].date));
printf("\n");
}
int main(void) {
int songCount, menuOption;
Song *x = NULL;
printf("1. insert song\n 2. load from file\n ");
scanf("%d", &menuOption);
switch (menuOption) {
case 1:
printf("Insert how many songs do you want to input?\n");
if (scanf("%d", &songCount) == 1) {
x = calloc(songCount, sizeof(Song));
for (int i = 0; i < songCount; i++) {
insertSong(x, i);
}
saveToFile(x, songCount);
}
break;
case 2:
readSong(&x, &songCount);
break;
}
free(x);
x = NULL;
return 0;
}