I have to add an array of int passed as parameter in a binary file as argument of the function. In parameter of the function there is also the size of the array. If the file is empty we write the array but if the file already contains an array, we concatenate the two arrays. My concern is that at each execution, I am reported a crash. Here is my code:
void appendIntArray(char* filename, int* array, int N){
int* buffer = (int*) malloc(sizeof(int)*200);
FILE* fp;
if(fp == NULL) {
return(N);
}
fp = fopen(filename, "rb");
fread(N, sizeof(int), 1, fp);
fread(buffer, sizeof(int), N, fp);
fclose(fp);
fp = fopen(filename, "wb");
fwrite(&N, sizeof(int), 1, fp);
fwrite(buffer, sizeof(int), 1, fp);
fwrite(array, sizeof(int), N, fp);
fclose(fp);
return(N, buffer,array);
}
` Could someone please tell me why my program crashes and correct me.
If the file is empty we should have an array. If the file already contains an array, I should have two arrays concatenated.
Before allocating the buffer, read the current length from the file. Add
Nto that to get the size of the final resulting array, and use that inmalloc(). Then you can usememcpy()to copy the new array to the end of the buffer after the old file contents.To return the new
Nto the caller, pass this parameter as a pointer.You need to call
fopen()before you check iffpis null.To return the new array of file contents, you have to declare the function to return
int *, notvoid.