Jump to content

Ler ficheiro binário


zephirus
 Share

Recommended Posts

Boas,

Sou bastante noob nestas questões do C++. Peço desde já desculpa se a pergunta não fizer sentido mas gostava de saber como ler um ficheiro binário muito grande (formato double), e conseguir fazer o seu display.

Testei este código mas obtenho apenas zeros:

FILE * pFile;
  long lSize;
  double * buffer;
  size_t result;

  pFile = fopen("data.bin" ,"rb");
  if (pFile==NULL) {fputs ("File error",stderr); exit (1);}


   //obtain file size:
  fseek (pFile , 0 , SEEK_END);
  lSize = ftell (pFile);
  rewind (pFile);

   /*allocate memory to contain the whole file:*/

  buffer = (double*) malloc (sizeof(double)*lSize);
  if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

int i,rc;
  for (i = 0; (rc = getc(pFile)) != EOF && i < 5; buffer[i++] = rc);
  fclose(pFile);
  if (i == 5) {
    puts("The bytes read were...");
    printf("%x %x %x %x %x\n", buffer[1000], buffer[1], buffer[2], buffer[340], buffer[4]);
  } else
    fputs("There was an error reading the file.\n", stderr);
  return EXIT_SUCCESS;
Link to comment
Share on other sites

Já reparaste nos warnings que dá?

teste.c: In function ‘main’:

teste.c:30: warning: format ‘%x’ expects type ‘unsigned int’, but argument 2 has type ‘double’

teste.c:30: warning: format ‘%x’ expects type ‘unsigned int’, but argument 3 has type ‘double’

teste.c:30: warning: format ‘%x’ expects type ‘unsigned int’, but argument 4 has type ‘double’

teste.c:30: warning: format ‘%x’ expects type ‘unsigned int’, but argument 5 has type ‘double’

teste.c:30: warning: format ‘%x’ expects type ‘unsigned int’, but argument 6 has type ‘double’

teste.c:9: warning: unused variable ‘result’

Depois estás ali a aceder ao buffer[1000] e buffer[340] quando só estás a colocar no buffer informação até ao índice 4 inclusivé.

Por último, isto de C++ tem pouco.

Link to comment
Share on other sites

é impressão minha ou aquilo é mais c do que c++? lolololololol 🙂

Bom, isso não ajuda nada. Eu disse no meu post que não estava muito dentro disto, aliás, esta questão foi-me pedida por uma pessoa que não podia no momento colocá-la aqui. Se alguém puder ajudar, óptimo, se for para fazer comentários vazios, escusam de escrever.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.