Read and write from file in C langage -


please, 1 can explain me why program not work ? i'm trying read , write file using r+. file test.txt exists , writing executed correctly. however, reading not work.

int main() {      file* fichier = null;     int age, taille_max=10;     char chaine[taille_max];      fichier = fopen("test.txt", "r+");     if (fichier != null)     {          printf("give age ? ");         scanf("%d", &age);         fprintf(fichier, "hello have %d year old", age);          while (fgets(chaine, taille_max, fichier) != null)         {             printf("%s", chaine); //does not print         }fclose(fichier);     }      return 0; } 

by not work mean not display thing ! if file contains sentence have ... year old. there no error. program not print content of file

you writing , reading file @ same time, not practice, reason code not work because of buffering. fprintf(fichier, "hello have %d year old", age); not happening until fclose(fichier) statement happening. added 2 statements code, see below. once fprintf file pointer fichier not @ end of file wrong place next thing try read age number wrote, have move file pointer fichier somehow - used rewind work if test.txt newly created file. otherwise need method of moving file pointer fichier backwards enough read wrote.

int main() {  file* fichier = null; int age, taille_max=10; char chaine[taille_max];  fichier = fopen("test.txt", "r+"); if (fichier != null) {      printf("give age ? ");     scanf("%d", &age);     fprintf(fichier, "hello have %d year old", age);      fflush( fichier );  /* force  write file */     rewind( fichier );  /* rewind file pointer beginning */      while (fgets(chaine, taille_max, fichier) != null)     {         printf("%s", chaine); //does not print     } } fclose(fichier); return 0; } 

in original code, statement

while (fgets(chaine, taille_max, fichier) != null) 

fails read , returns null, printf("%s", chaine); not happen. happening because of output buffering , fprintf() statement not happening when think should.

this output buffering normal , if want printf happen @ exact moment need use fflush() read here learn more: why printf not flush after call unless newline in format string?


Comments

Popular posts from this blog

c# - Update a combobox from a presenter (MVP) -

How to understand 2 main() functions after using uftrace to profile the C++ program? -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -