I need help with modules in C.
I made a little manager system where I save records about school subjects. I have my saveToFile
and readFromFile
functions in one (main.c)
C file. Now I was asked to create a module for reading and writing functions. I created SavingFunctions.c
SavingFunctions.h
and also I was asked to create an object file .o
but I don't get it if I need to write it to myself or just do nothing, because I see some files with .o in my folder. Also, I use structure, maybe I need to put it in a separate file?
SavingFunctions.c
#include <stdio.h>
#include <stdlib.h>
#include "SavingFunctions.h"
//READ_FUNCTION
int numberOfRecords(struct Subjects DataBase[])
{
FILE *fp = NULL;
fp = fopen("file.bin", "rb");
if(fp == NULL)
{
printf("Error! Failed to open\find the file.
");
exit(1);
}
int i=0;
//Reads the contents of a structure variable from file
while(fread(&DataBase[i], sizeof(DataBase[i]),1, fp) == 1)
{
++i;
}
fclose(fp);
return i;
}
//WRITE_FUNCTION
void writeTofile(struct Subjects DataBase[], int positionToWrite)
{
int recordsNumber;
FILE *fp;
fp = fopen("file.bin", "wb");
if(fp == NULL)
{
printf("Error! Failed to open or find the file.
");
exit(1);
}
recordsNumber = 0;
for(int i=0; i<=positionToWrite;++i)
{
fwrite(&DataBase[i], sizeof(Subjects), 1, fp);
recordsNumber++;
}
fclose(fp);
printf("Total number of items in the file: %d
", recordsNumber);
}
SavingFunctions.h
typedef struct Subjects
{
char Lesson[20];
char TeachersName[20];
char TeachersLastName[20];
int Credits;
int NumberOfStudents;
} Subjects;
#ifndef SAVINGFUNCTIONS_H
#define SAVINGFUNCTIONS_H
int numberOfRecords(struct Subjects DataBase[]);
void writeTofile(struct Subjects DataBase[], int positionToWrite);
#endif
question from:
https://stackoverflow.com/questions/65859454/how-to-create-module-in-c 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…