Is it possible to open the file for writing and at the same time open for reading without before closing in C?

Asked

Viewed 196 times

2

Not a good programming practice?

void leitura(FILE *arq)
{
  if((arq = fopen("dificuldade.txt","r")) == NULL)
    printf("Erro ao abrir o arquivo\n"); 
  else
  {
    //linhas de codigo
    fclose(arq); 
  }
}

void impressao(FILE *arq)
{
  int i;

  if((arq = fopen("dificuldade.txt","w")) == NULL)
    printf("Erro ao abrir o arquivo\n");
  else
  {
    for(i=0; i<10; i++)
       {
         //linhas de codigos
         leitura(arq); 
         //Estou no loop e quero fazer a leitura a cada impressão
         //Cada impressão no ciclo, quero ler e manipular aqueles dados
         //Como faço isso, pois tenho que fechar o arquivo... ?
       }
    fclose(arq);
  }
}

main()
{
  FILE *arq;
  impressao(arq);
  return 0;
}
  • You should use "r+", to read and write, preserving the original content

  • On all put "r+" and the "fclose" stays where it is? without closing the file during printing to then read?

  • Opens the file only once with "r+", and works with fputs(), fgets() and etc..

  • If after writing you want to go back to the beginning of the file use the Rewind function.

1 answer

0


It is good practice to close every time you open a text file. With the attached table you can see some features you can implement to read and write.

inserir a descrição da imagem aqui

These functions below are used to read and write to the text file.

void fprintf (FILE *fluxo, char *formatação, ...);
int fwrite (void *dados, int tamanho_do_elemento, int num_elementos, FILE *fluxo);

More information about text files Wikibooks

  • It is difficult to implement it there in the code, because I have to open the file and make the impression and with it open I have to read and manipulate the data...

Browser other questions tagged

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