I was trying to write a code for:
read in N numbers from a file FILE1 into an array(dynamic)
then sort those numbers
then search for numbers (1 per line, given in FILE2) in the array.
#include <stdio.h>
#include <stdlib.h>
#include<math.h>
#include<string.h>
int main(int argc, char* argv[])
{
FILE *fp1=fopen("myFile1.txt", "r");
if (fp1 == NULL)
{
printf("cannot open this file");
exit(0);
}
FILE *fp2 = fopen("test1.txt", "w");
if (fp2 == NULL)
{
puts("Not able to open this file");
exit(1);
}
int i=0,num,j,k;
int *B=NULL;
int *C;
int a;
int size=32;
B = malloc(sizeof(int)*size);
while (fscanf(fp1, "%d", &num) == 1)
{
if (i<size)
{
B[i]=num;
fprintf(fp2,"%d\r\n",num);
i++;
}
else
{
C = malloc(sizeof(int)*2*size);
memcpy( C, B, size*sizeof(int)) ;
free(B);
B=&C[0];
B[i]=num;
i++;
size=size*2;
i++;
for (j=0; j<size; ++j)
{
for (k=j+1; k<size; ++k)
{
if (B[j] < B[k])
{
a= &B[j];
B[j] = B[k];
B[k] = a;
}
}
}
printf ("after sorting");
for (j=0; j<size; ++j)
printf ("%d\n", B[j]);
}
}
return 0;
fclose(fp1);
fclose(fp2);
}
Reading from a file and store into an array(dynamic) part is executed very correctly. But now I am not able to understand how to sort these numbers. I am trying to apply bubble sort but it will put 0s in my array, may be I am not implementing it correctly.
aalekh 0 Newbie Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.