Good evening,
I'm working with C, and it turns out that I have a function or method that you have to print the data, the meal markings, for students who book a meal on the system.
In the method the system must check if this file is empty and if it is empty it simply prints to the file fprintf(filetmp, "%d %s %s %s \n", num, nome, subnome, meal);
If the file already has, for example, two meals marked by the students, the system must read and print them to filetmp
I have tried to compare the file to see if it is empty, or if you have a meal, I checked and consulted the internet for it and although it exists, I know a ftell(file)
function that allows determining how file is empty or no I can not in any way test whether the file has a meal or not.
I also tried feof(file)
but it happens that I just run out of the file. How can I change the code for it to check if the file is empty, and to check if the file has any meals.
void PrintMealToFIle(int num, char nome[100], char subnome[250])
{
size_t size;
int i=0, j=0;
struct Food f;
struct CantinaAlunoFood aluno;
const char *filename = "db-cantinameals.txt";
FILE *file, *filetmp;
filetmp = fopen("cantinatmp.txt", "w");
file = fopen(filename, "r");
size = ftell(file);
fseek(file, 0, SEEK_END);
//size = ftell(file);
while (!(feof(file)))
{
if (ftell(file)==0)//se esta vazio
//fseek(file, 0, SEEK_END);
//size = ftell(file);
fprintf(filetmp, "%d %s %s %s \n", num, nome, subnome, meal);
if (ftell(file)!=0)
{
fscanf(file, "%d %s %s %s ", &aluno.id, aluno.name, aluno.subname, aluno.refeicao);
fprintf(filetmp, "%d %s %s %s \n", num, nome, subnome, meal);
fclose(filetmp);
fclose(file);
if (remove(filename) == 0)
{
printf("\n");
printf("Ficheiro removido com sucesso\n");
}
else
perror("Problema a remover ficheiro ");
if (rename("cantinatmp.txt", filename) == 0)
{
printf("\n");
printf("Ficheiro bem renomeado");
}
else
perror("Problema ");
}
}
}