i have to write a code to make an external merge sort. This part is phase 1 where it writes {num_blocos} files with 400KB sorted files:
char file_name[20];
while (1)
{
size_read = fread(bloco, tam, mem_bloco, file);
if (size_read != 0)
{
heapSort(bloco, size_read);
sprintf(file_name, "file%drun0.bin", num_blocos);
temp = fopen(file_name, "wb");
fwrite(bloco, tam, size_read, temp);
num_blocos++;
fclose(temp);
}
else
{
break;
}
}
and this is phase 2 where it merge all files {n by n} each run or rewrite it to the next run.
int k = 0, n = 1, j = 0;;
char file_write[20], file_read[20];
while (n < num_blocos)
{
while (k<num_blocos)
{
sprintf(file_write, "file%drun%d.bin", k, n);
file = fopen(file_write, "wb");
if (k + 1 == num_blocos)
{
sprintf(file_read, "file%drun%d.bin", k, j);
temp = fopen(file_read, "rb");
int size = fread(bloco, tam, mem_bloco, temp);
fwrite(bloco, tam, size, file);
break;
}
else
{
mergeSortFile(k, k + n, file, j);
sprintf(file_name, "file%drun%d.bin", k, j);
remove(file_name);
sprintf(file_name, "file%drun%d.bin", k+n, j);
remove(file_name);
k += 2 * n;
}
}
k = 0;
j = n;
n *= 2;
fclose(temp);
fclose(file);
remove(file_read);
}
My problem comes here:
FILE *tempa, *tempb;
char file_name[20];
sprintf(file_name, "file%drun%d.bin", posb1, j);
tempa = fopen(file_name, "wb+");
if( tempa == NULL ) {
fprintf(stderr, "Couldn't open %s: %s\n", file_name, strerror(errno));
exit(1);
}
sprintf(file_name, "file%drun%d.bin", posb2, j);
tempb = fopen(file_name, "wb+");
if( tempb == NULL ) {
fprintf(stderr, "Couldn't open %s: %s\n", file_name, strerror(errno));
exit(1);
}
When my original file has 1MB it works well, but when it has 99MB that is the size i want or even 6MB, it gives me segmentation fault, following debug i found it was when the tempb fopen tries to open the file "file10run1.bin" in 6 or more MB, someone could give me a light?