guys! So I have an assignment to create a structure that includes variables based on what information I need to store and to bring out a menu that calls different functions and does different things. The problems is that for some reason my createFile function is not working at all and I've been looking for errors for 2 days and I simply cannot spot where this is coming from.
Ignore the changeStud funcion as I'm still working on it. I simply want to create my file when I enter the name for it and then chose the nnumber of the function. (in my case > enter filename> enter 1> it just loops the menu function and it should create a file)
#define _CRT_SECURE_NO_WARNINGS
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student {
char ime[50];
char fn[10];
int ocfiz, ocmat, ocpro;
};
char filename[20];
FILE *fd;
Student ps;
void createFile() {
fd = fopen(filename, "wb");
fclose(fd);
printf("File created!\n");
}
void readStud(Student *s) {
printf("Enter data for new student");
getchar();
printf("Enter student name:");
gets_s(s->ime);
printf("\nEnter FN:");
scanf_s("%s", s->fn);
printf("\nEnter marks for Maths, Programming, Physics");
scanf_s("%d %d %d", &s->ocmat, &s->ocpro, &s->ocfiz);
getchar();
}
void addStud() {
fd = fopen(filename, "a+b");
char c;
do {
readStud(&ps);
fwrite(&ps, sizeof(ps), 1, fd);
printf("More Students? (y/n) : ");
c = getchar(); getchar();
} while (c == 'y');
fclose(fd);
}
void writeAllStud() {
fd = fopen(filename, "rb");
printf("students in file\n");
fread(&ps, sizeof(ps), 1, fd);
while (!feof(fd)) {
printf("%s fn: %s ocmat: %d ocpro: %d ocfiz: %d", ps.ime, ps.fn, ps.ocmat, ps.ocpro, ps.ocfiz);
fread(&ps, sizeof(ps), 1, fd);
}
fclose(fd);
}/*
void changeStud() {
char fn2[50];
printf("enter FN:");
gets_s(fn2);
fd = fopen(filename, "r+b");
fread(&ps, sizeof(ps), 1, fd);
while (!feof(fd)) {
if (strcmp(ps.fn, fn2)==0) {
fseek(fd, -(long) sizeof(ps), SEEK_CUR);
fwrite(&ps, sizeof(ps, 1, fd));
break;
}
}
}*/
void Avg() {
}
void exportData() {
FILE *txt;
txt = fopen("students.txt", "wt");
fd = fopen(filename, "rb");
fread(&ps, sizeof(ps), 1, fd);
while (!feof(fd)) {
fprintf(txt, "%s %s marks fiz%d mat%d prog%d\n", ps.fn, ps.ime, ps.ocfiz, ps.ocmat, ps.ocpro);
fread(&ps, sizeof(ps), 1, fd);
}
fclose(fd);
fclose(txt);
printf("students have been written to a text file.\n");
}
void main() {
printf("Enter file name:");
gets_s(filename);
int c;
do {
printf("\nMenu:\n");
printf("0 Exit\n");
printf("1 Create file\n");
printf("2 Add new student data\n");
printf("3 Change data from FN\n");
printf("4 AVG marks for maths, programming, physics\n");
printf("5 export all AVG marks to .txt file\n");
scanf("%d", &c);
switch (c) {
case 1: createFile; break;
case 2: addStud; break;
//case 3: changeStud; break;
case 4: Avg; break;
case 5: exportData; break;
}
} while (c != 0);
}
i think you should use your struct variable like this:
struct Student {
char ime[50];
char fn[10];
int ocfiz, ocmat, ocpro;
}ps;
or use
struct Student ps;
instead of just student ps,or you can decleare it in main function..And passing a struct in a functin is
void readStud( struct Student *s)() {
//your code...
}
Related
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1000
int write()
{
char team_name[50];
int i,n;
printf("------------------------------------------------------");
printf("\n");
printf("Enter number of Teams: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("Team_Detail.txt","a"));
if(fptr==NULL)
{
printf("Error!");
exit(1); // exit(1) (usually) indicates unsucessful termination. However, it's usage is non-portable.
}
for (i=0;i<n;++i)
{
printf("------------------------------------------------------");
printf("\n");
fflush(stdin);
printf("Enter the Team Name:-");
scanf("%[^\n]",team_name);
}
fclose(fptr);
return 0;
}
int display()
{
FILE * fptr;
char buffer[BUFFER_SIZE];
int totalRead = 0 ;
fptr = fopen("Team_Detail.txt","r");
if(fptr == NULL)
{
printf("Unable to open file.\n");
printf("Please check whether file exists or no");
exit(EXIT_FAILURE);
}
printf("------------------------------------------------------");
printf("\n");
while(fgets(buffer, BUFFER_SIZE, fptr ) != NULL)
{
totalRead = strlen(buffer);
buffer[totalRead - 1] = buffer[totalRead - 1] == '\n'
? '\0'
: buffer[totalRead - 1];
printf("%s\n", buffer);
printf("------------------------------------------------------------------------------------------------------------------");
printf("\n");
}
fclose(fptr);
return 0;
}
int main()
{
printf("------------------------------------------------------");
printf("\nFootball League System\n");
printf("------------------------------------------------------");
int choice, num, i;
while(1)
{
printf("\n");
printf(" Press 1 to Enter the Details of the Team \n");
printf(" Press 2 to Display Team Details \n");
printf(" Press 3 to Exit \n");
printf("------------------------------------------------------");
printf("\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
write(); // Here, Calling "team_attributes()" Function
break;
case 2:
display();
break;
case 3:
printf("program finished\n");
exit(0);
break;
default:
printf("Invalid Input entered\n");
}
}
return 0;
}
with the above code I am able give my input and whatever input i give is stored in a temporary text file, but i am unable to display the dat which is present in the temporary text file, Can you guys please help me with this. And also can anyone please suggest me the logic for scheduling matches between the teams by fetching the data of teams temporary text file .
-in your write() you are getting input through scanf(), but not writing them in txt file.
-use functions like fputs() to write the data in txt file.
I'm adding this code to write data in txt file
fputs(team_name,fptr);
Modified version:
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1000
int write()
{
char team_name[50];
int i,n;
printf("------------------------------------------------------");
printf("\n");
printf("Enter number of Teams: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("Team_Detail.txt","a"));
if(fptr==NULL)
{
printf("Error!");
exit(1); // exit(1) (usually) indicates unsucessful termination. However, it's usage is non-portable.
}
for (i=0;i<n;++i)
{
printf("------------------------------------------------------");
printf("\n");
fflush(stdin);
printf("Enter the Team Name:-");
scanf("%[^\n]",team_name);
fputs(team_name,fptr);
}
fclose(fptr);
return 0;
}
int display()
{
FILE * fptr;
char buffer[BUFFER_SIZE];
int totalRead = 0 ;
fptr = fopen("Team_Detail.txt","r");
if(fptr == NULL)
{
printf("Unable to open file.\n");
printf("Please check whether file exists or no");
exit(EXIT_FAILURE);
}
printf("------------------------------------------------------");
printf("\n");
while(fgets(buffer, BUFFER_SIZE, fptr ) != NULL)
{
totalRead = strlen(buffer);
buffer[totalRead - 1] = buffer[totalRead - 1] == '\n'
? '\0'
: buffer[totalRead - 1];
printf("%s\n", buffer);
printf("------------------------------------------------------------------------------------------------------------------");
printf("\n");
}
fclose(fptr);
return 0;
}
int main()
{
printf("------------------------------------------------------");
printf("\nFootball League System\n");
printf("------------------------------------------------------");
int choice, num, i;
while(1)
{
printf("\n");
printf(" Press 1 to Enter the Details of the Team \n");
printf(" Press 2 to Display Team Details \n");
printf(" Press 3 to Exit \n");
printf("------------------------------------------------------");
printf("\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
write(); // Here, Calling "team_attributes()" Function
break;
case 2:
display();
break;
case 3:
printf("program finished\n");
exit(0);
break;
default:
printf("Invalid Input entered\n");
}
}
return 0;
}
I have this code, and want that the program reads/loads the data that is on the file and them printed them, but this didn´t work.
I can´t write on the file, but can´t read it.
I want that when the program initialize, he already have loaded the info that is in the the binary file, so the user can use it, for example for searching people.
#include <stdio.h>
#include <stdlib.h>
#define MAX_PERSON 3
#define FILENAME "person.bin"
typedef struct {
int id;
char fname[20],lname[20];
}person;
typedef struct {
int counter;
person persons[MAX_PERSON];
}Persons;
int writeStruct(Persons *persons,char *file){
FILE *outfile;
outfile = fopen (file, "ab+");
if (outfile == NULL){
exit(EXIT_FAILURE);
}
printf("\nInsira a informações da pessoa \n");
printf("Código: ");
scanf("%d", &persons->persons[persons->counter].id);
printf("Primeiro Nome: ");
scanf("%s", persons->persons[persons->counter].fname);
printf("Último Nome: ");
scanf("%s", persons->persons[persons->counter].lname);
fwrite (&persons, sizeof(Persons), persons->counter, outfile);
if(fwrite != 0){
puts("Sucess on writing on file");
}else{
puts("Error on writing on file");}
fclose (outfile);
return persons->counter++;
}
void loadStruct(Persons *persons,char *file){
FILE *infile;
// Open person.bin for reading
infile = fopen(file, "rb+");
if (infile == NULL) {
fprintf(stderr, "\nError opening file\n");
exit(1);
}
// read file contents till end of file
fread(&persons, sizeof (Persons), persons->counter, infile);
// close file
fclose(infile);
}
void listPersons(Persons persons){
int i;
puts("Lista de pessoas");
puts("-----------------");
for(i=0;i < persons.counter; i++) {
printPerson(persons.persons[i]);
}
puts("-----------------");
}
void searchPeople(Persons persons) {
int number;
printf("Indique o código da pessoa que pretende procurar: ");
scanf("%d",&number);
number = searchPerson(persons,number);
if (number != -1) {
printPerson(persons.persons[number]);
} else {
puts(ERROR_PERSON_NOT_EXISTS);
}
}
int searchPerson(Persons persons,int number) {
int i;
for (i = 0; i < persons.counter; i++) {
if (persons.persons[i].id == number) {
return i;
}
}
return -1;
}
void printPerson(person person){
printf("%d - %s %s\n", person.id,person.fname, person.lname);
}
int main ()
{
int op;
Persons persons ={.counter = 0};
loadStruct(&persons,FILENAME);
do{
puts("PESSOAS - BASE DE DADOS");
puts("-----------------");
puts("2 - Inserir pessoa");
puts("3 - Listar pessoas");
puts("4 - Procurar pessoa");
puts("0 - Sair");
puts("-----------------");
printf("Nº Pessoas: %d/%d \n", persons.counter, MAX_PERSON);
printf("Opção:");
scanf("%d",&op);
printf("\n");
switch (op) {
case 0:
exit(0);
break;
case 2:
writeStruct(&persons,FILENAME);
break;
case 3:
listPersons(persons);
break;
case 4:
searchPeople(persons);
break;
default:
puts("Opção inválida!");
break;
}
}while(op!=0);
}
You're just writing one Persons structure to the file. You shouldn't use persons->counter as the number of items that you're writing or reading, as the array is entirely contained in the structure.
You also shouldn't open the file in append mode. Since you're writing the entire Persons structure, not a single person, you should open it in write mode and overwrite the whole file.
The first argument to fwrite() and fread() should be persons, not &persons, since you want to fill in the structure that it points to, not overwrite the pointer.
To make sure you don't write outside the array, you should check that persons->counter hasn't exceeded the size of the array.
int writeStruct(Persons *persons,char *file){
FILE *outfile;
if (persons->counter >= MAX_PERSON) {
puts("File is full\n");
return persons->counter;
}
outfile = fopen (file, "wb");
if (outfile == NULL){
exit(EXIT_FAILURE);
}
printf("\nInsira a informações da pessoa \n");
printf("Código: ");
scanf("%d", &persons->persons[persons->counter].id);
printf("Primeiro Nome: ");
scanf("%s", persons->persons[persons->counter].fname);
printf("Último Nome: ");
scanf("%s", persons->persons[persons->counter].lname);
fwrite (persons, sizeof(Persons), 1, outfile);
if(fwrite == 1){
puts("Success on writing on file\n");
}else{
puts("Error on writing on file\n");
}
fclose (outfile);
return persons->counter++;
}
void loadStruct(Persons *persons,char *file){
FILE *infile;
// Open person.bin for reading
infile = fopen(file, "rb");
if (infile == NULL) {
fprintf(stderr, "\nError opening file\n");
exit(1);
}
// read file contents till end of file
fread(persons, sizeof (Persons), 1, infile);
// close file
fclose(infile);
}
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);
}
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);
};
#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;
}