Reputation: 173
I try to read a bin file with a function. The functions gets the filename and the address of a array in the main function. The function is showing me the right bytes but the methode which I use to fill the array from the main-function is a failure. Can someone help me and explain, because I suck at pointers etc.
When I use a bin file with the following bytes: 00 00 05 20
The functions-printf gives me the right bytes, but the dataarray has the following value: 0 5 0 0
#include <stdio.h>
#include <stdlib.h>
#define MAX_BYTES_IN_FILE 10000
int get_byte_from_file(FILE *stream, int *dataarray) {
int counter = 0, datastream[MAX_BYTES_IN_FILE];
while( ( datastream[counter]=fgetc(stream)) != EOF){
printf("%d ", datastream[counter]);
dataarray[counter] = datastream[counter];
counter += 1;
}
printf("\n\n\n");
return counter;
}
int main(int argc, char **argv) {
FILE *datei;
char filename[255];
int number_of_bytes;
int* dataarray[MAX_BYTES_IN_FILE];
datei=fopen(argv[1],"r");
number_of_bytes = get_byte_from_file(datei, &dataarray);
for (int i=0;i<number_of_bytes;i++)
printf("%d ",dataarray[i]);
return EXIT_SUCCESS;
}
Upvotes: 0
Views: 47
Reputation: 75062
I don't think you have reasons to use arrays of pointers here.
Also binary files should be opened in binary mode and it should be checked whether opening file is successful.
Try this instead of your main
function:
int main(int argc, char **argv) {
FILE *datei;
char filename[255];
int number_of_bytes;
int dataarray[MAX_BYTES_IN_FILE]; /* use an array of integers instead of an array of pointers */
if (argc < 2) { /* check if we have valid argv[1] */
fputs("no file name given\n", stderr);
return EXIT_FAILURE;
}
datei=fopen(argv[1],"rb"); /* use rb instead of r to use binary mode */
if (datei == NULL) { /* check if opening file suceeded */
fputs("file open failed\n", stderr);
return EXIT_FAILURE;
}
/* you should remove & here, and this array will be converted to a pointer to the first element */
number_of_bytes = get_byte_from_file(datei, dataarray);
for (int i=0;i<number_of_bytes;i++)
printf("%d ",dataarray[i]);
return EXIT_SUCCESS;
}
Upvotes: 2