6
Good night,
I’m working with C, and it turns out I have a function or method that you have to print to a file the data, the meal appointments,.
In the method the system has to check if that file is empty and if it is empty simply prints to the file fprintf(filetmp, "%d %s %s %s \n", num, nome, subnome, meal);
If the file already has for example 2 meals marked by the students, the system has to read and print them also to filetmp
It turns out I’ve tried to compare the file by checking if it’s empty, or if it has any meals, I checked and consulted the internet for this and even though it exists, I know a function ftell(file)
which allows to determine as it seemed to me whether the file is empty or not I am not in any way able to test whether or not the file has any refection.
I also tried the feof(file)
but it turns out I just lose the file. I wonder how I can change the code 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 ");
}
}
}
I won’t even try to analyze the code because it seems to be in a semi-finished state but the path you are trying seems correct. I think you would need to further detail the problem or produce code that is easier to analyze. http://answall.com/help/mcve Do
fseek(file, 0, SEEK_END); if(ftell(file) == 0)
certainly works.– Maniero
fopen(..., "a")
... open the file in mode "append" adds what is written at the end of what already exists there.– pmg