Reputation: 21
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.
Upvotes: 2
Views: 456
Reputation: 781058
Before allocating the buffer, read the current length from the file. Add N
to that to get the size of the final resulting array, and use that in malloc()
. Then you can use memcpy()
to copy the new array to the end of the buffer after the old file contents.
To return the new N
to the caller, pass this parameter as a pointer.
You need to call fopen()
before you check if fp
is null.
To return the new array of file contents, you have to declare the function to return int *
, not void
.
char *appendIntArray(char* filename, int* array, int *N){
FILE* fp = fopen(filename, 'rb');
if(!fp) {
return NULL;
}
int currentsize;
fread(¤tsize, sizeof(int), 1, fp);
int* buffer = (int*) malloc(sizeof(int)*(currentsize + *N));
if (!buffer) {
return array;
}
fread(buffer, sizeof(int), currentsize, fp);
fclose(fp);
fp = fopen(filename, "wb");
if (!fp) {
return NULL;
}
memcpy(&buffer[currentsize], array, N * sizeof(int));
*N += currentsize;
fwrite(N, sizeof(int), 1, fp);
fwrite(buffer, sizeof(int), *N, fp);
fclose(fp);
return buffer;
}
Upvotes: 1