Davey_flan
Davey_flan

Reputation: 1

How to read a file line by line, append each line to a vector and then implement MPI code

So I'm attempting to make a C program to read in a file which is a number of integers in the format where the first value is the length of the file and the following lines are random integers for example:

4
2
7
8
17

or

3
9
23
14

What I want to do is to read in the file, append each line to a vector. I'll later split the vector into equal sizes and distribute them across a number of MPI processes for further tasks.

I currently have tried counting the number of lines in the file and then creating a vector to store all the elements of the file via a for loop. However this has not worked. I would greatly appreciate any help. My attempt is below:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <mpi.h>



int main( int argc, char *argv[]) {

     int rank, world_size;
     
     int root;
     int i;

     MPI_Init( &argc, &argv );
     MPI_Comm_rank( MPI_COMM_WORLD, &rank);

    if (rank == 0) { 
        
       char Line[100];
       char c;
       int count_lines=0;
       FILE *fp = fopen("Input_16.txt","r");
       for (c = getc(fp); c != EOF; c = getc(fp))
        if (c == '\n') // Increment count if this character is newline
           count_lines = count_lines + 1;
       
       int array[count_lines];
       for (i=0; i<count_lines; i++)
           array[i]=fgets(Line,100,fp);
           printf("Prints: %c \n",array[i]); 
           

}


    MPI_Finalize();
}

Upvotes: 0

Views: 80

Answers (1)

user9706
user9706

Reputation:

I don't know anything about MPI but here is how you would read the file:

int read_file(const char *path, size_t *len, int **a) {
    *a = NULL;
    FILE *fp = fopen(path,"r");
    if(!fp)
        return 0;
    if(fscanf(fp, "%zu", len) != 1) {
        printf("fscanf of len failed\n");
        goto err;
    }
    if(!*len) {
        printf("len == 0\n");
        goto err;
    }
    *a = malloc(*len * sizeof **a);
    if(!*a) {
        printf("malloc failed\n");
        goto err;
    }
    for(size_t i = 0; i < *len; i++) {
        if(fscanf(fp, "%d", &(*a)[i]) != 1) {
            printf("fscanf of item %zu failed\n", i);
            goto err;
        }
    }
    fclose(fp);
    return 1;
err:
    free(*a);
    if(fp) fclose(fp);
    return 0;
}

int main( int argc, char *argv[]) {
    size_t len;
    int *a;
    if(!read_file("Input_16.txt", &len, &a)) {
        printf("file read failed\n");
        return 1;
    }

    for(size_t i = 0; i < len; i++) {
        printf("%d\n", a[i]);
    }
}

and example run:

2
7
8
17

Upvotes: 1

Related Questions