How to check in C if the file is empty?

Asked

Viewed 5,045 times

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.

  • fopen(..., "a") ... open the file in mode "append" adds what is written at the end of what already exists there.

2 answers

5

You can check which file size and then check if it is empty.

int get_size(const char* file_name)
{
    FILE *file = fopen(file_name, "r");

    if(file == NULL)
        return 0;

    fseek(file, 0, SEEK_END);
    int size = ftell(file);
    fclose(file);

    return size;
}

Example, by checking the file teste.txt is empty:

if(get_size("teste.txt") == 0)
{
    printf("O arquivo esta vazio.");
}
else
{
    printf("O arquivo nao esta vazio.");
}

1

You can do a basic repetition system to check if there is something existing in the file

int main(){

   char Arquivo(Array);    //Variáveis
   int i=0;

   FILE *Abrir;   //Abrir e ler o arquivo
   Abrir=fopen(Arquivo,"rt");

      fscanf(Abrir,%c,&Arquivo(i));

      if (Arquivo(i) == Null){ // Condição Se
         printf("Arquivo Vazio");
      } else {printf("Arquivo com dados");}
      break;

   printf("A partir daqui vc resolve o que fazer");

   fclose(Abrir);   //fechando ponteiro
   return 0;
}
  • 1

    That break Inside your loop will not work very well, I have not tested but only 'hit the eye' you can see that the loop will be rotated only once.

  • This code has other errors.

  • I don’t think this code Compile the way it is.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.