I am trying to do sort key-value pairs with qsort. Every proc reads in files with filenames as the proc ids. MPI_Gather sends all the read values to proc 0, which sorts the keys and stores the key-val pairs in a file called "Output". The gather however, does not seem to work. Any help is appreciated. Thanks!
I run the code as
mpirun -np 3 ./a.out
and my input files are: File "0":
21 bbbb
2119 iiii
120 hhhh
File "1":
40 dddd
10 aaaa
100 gggg
File "2":
32 cccc
44 eeee
99 ffff
And the code is:
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#define BUFSIZE 3
#define BUFLEN 255
struct keyval{
int key;
char val[BUFLEN];
};
typedef struct keyval keyval_s;
typedef int (*compareptr)(const void*, const void*);
int compare (keyval_s * a, keyval_s * b)
{
return ( a->key - b->key );
}
int main (int argc, char *argv[])
{
int values[BUFSIZE];
keyval_s kv[BUFSIZE], *recv;
int n, i=0, temp;
FILE *in, *out;
int rank, size;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
char filename[20];
char data[20];
if(rank ==0){
recv = (keyval_s *) malloc (size*BUFSIZE*sizeof(keyval_s));
}
sprintf(filename, "%d", rank);
in=fopen(filename,"r");
while(fscanf(in,"%d %s",&kv[i].key, kv[i].val) != EOF){
printf("Read key %d, data %s from file\n", kv[i].key, kv[i].val);
i++;
}
MPI_Gather(kv,BUFSIZE,MPI_BYTE,recv,BUFSIZE,MPI_BYTE,0,MPI_COMM_WORLD);
if(rank==0){
qsort ((void*)&kv, BUFSIZE, sizeof(keyval_s),(compareptr) compare);
out=fopen("Output","w");
for (n=0; n<BUFSIZE*size; n++)
fprintf (out,"%d %s\n",recv[n].key, recv[n].val);
free(recv);
fclose(out);
}
fclose(in);
return 0;
}