Search code examples
printffgetc

inverted results when using many fgetc inside the same printf


I have a file archivo3.txt with "ABCDEFGHI", I read the 3 first characters though fgetc SEPARATELY (differents printf) and works properly (41, 42, 43 are displyaed), the problem comes when I try to do the same but using only one printf.

In that case the values are displayed from rigth to left (43,42,41). Does anybody know what happens?

My code is:

#include<stdio.h>
#include<stdlib.h>

int main(){

  FILE*app_f=fopen("archivo3.txt", "rb");
  if(app_f==NULL){
    printf("error al abrir el archivo");
    exit(1);
  }else{
  fseek(app_f,0, SEEK_SET);
  printf("caracteres %02X\n", fgetc(app_f));
  printf("caracteres %02X\n", fgetc(app_f));
  printf("caracteres %02X\n", fgetc(app_f));
  printf("\n--------------\n");
  fseek(app_f,0, SEEK_SET);
  printf("caracter %02X, %02X, %02X\n", fgetc(app_f), fgetc(app_f), fgetc(app_f));
  }
  return 0;
}

Solution

  • The order that the parameters are evaluated is not defined in any standard and can thus vary from compiler to compiler. It seems your compiler is evaluating the expressions from last to first rather than the other way round. Another compiler may do so in a different order.

    It is thus safest not to assume the order in which the printf arguments will be evaluated, and to write your code accordingly. See my snippet below.

    For more info see this more thorough question

    #include<stdio.h>
    #include<stdlib.h>
    
    int main(){
      chars = char[3];
    
      FILE*app_f=fopen("archivo3.txt", "rb");
      if(app_f==NULL){
        printf("error al abrir el archivo");
        exit(1);
      }else{
      fseek(app_f,0, SEEK_SET);
      chars[0] = fgetc(app_f);
      chars[1] = fgetc(app_f);
      chars[2] = fgetc(app_f);
      printf("caracteres %02X\n", chars[0]);
      printf("caracteres %02X\n", chars[1]);
      printf("caracteres %02X\n", chars[2]);
      printf("\n--------------\n");
      fseek(app_f,0, SEEK_SET);
      printf("caracter %02X, %02X, %02X\n", chars[0], chars[1], chars[2]);
      }
      return 0;
    }