Assignments for parallel processing using OpenMPI.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
openmpi-assignments/readfile.c

71 lines
1.8 KiB

#include <stdio.h>
#include <stdlib.h>
#define INPUTFILE "sample1_e.in"
// Avoids aggresive memory reallocation at the beginning of buffer growth sequence
#define INIT_COUNT 8
// Optimal exponential buffer growth factor, 2 is sometimes used to
#define GROWTH_FACTOR 1.5
void *my_malloc(size_t size);
void *my_realloc(void *p, size_t size);
FILE *my_fopen(const char *filename, const char *mode);
int main(int argc, char *argv[]){
int number, count = 0, max = INIT_COUNT;
// Allocate enough memory for INIT_COUNT numbers
int *numbers = my_malloc(max * sizeof(int *));
FILE *file = my_fopen(INPUTFILE, "r");
// Read lines of numbers until an EOF or a character is read
while (fscanf(file, "%hd", &number) == 1) {
// Buffer space check
if (max == count) {
// Grow buffer exponentially
max *= GROWTH_FACTOR;
numbers = my_realloc(numbers, max * sizeof(int *));
}
// Store the read number to the array in memory
numbers[count++] = number;
}
//printf("count: %d, max: %d\n", count, max);
int i;
for (i = 0; i < count; i++) {
printf("%d ", numbers[i]);
}
return 0;
}
void *my_malloc(size_t size) {
void *p = malloc(size);
if (p == NULL) {
printf("Memory allocation unsuccessful.\n");
exit(EXIT_FAILURE);
}
return p;
}
void *my_realloc(void *p, size_t size) {
void *temp = realloc(p, size);
if (temp == NULL) {
printf("Insufficient memory; can't add more items.\n");
exit(EXIT_FAILURE);
}
return temp;
}
FILE *my_fopen(const char *filename, const char *mode) {
FILE *file = fopen(filename, mode);
if (file == NULL) {
printf("File %s could not be opened.\n", filename);
exit(EXIT_FAILURE);
}
return file;
}