I’d really like your help with the following problem.
I need to read N integers (in binary format) from two two binary files, and to write to another output file all the common integers(again in a binary format) in O(nlogn) time.
Here’s a sketch of what I want to do:
1-I know that I can’t use fscanf with %d, since these are not text files, but since I know that there are N numbers in each file, I want to run in a ‘for’ loop N times and
for (i=0; i<N; i++) {
fread(&int1, 4, 1, file1);
fread(&int2, 4, 1, file2);
arr1[i]=int1;
arr2[i]=int2;
}
Where arr1, arr2 are int arrays of N size each, Is this correct? If I know that there are N integers where every integer represented by 4 bits, I would finish at the end of the file, Am I?
2- I want to use qsort for sorting each array with nlogn steps, but then how should I compare between the two with still nlogn steps? I didn’t get to any smart way.
Your code is mostly correct, except it will not behave correctly when it reaches end-of-file.
freaddoes not detect EOF until you try to read past the end, so you should test the return value in case it reaches EOF or an error occurs, e.g.:You could also just slurp the entire arrays in a single
freadcall instead of looping, since the data is binary:For your second question, just place all of the integers into a single flat array. You can either do this by reading them directly into a single array, or copy them into one array after you’ve read in all of the data. Then
qsortthe combined array.