MA19
MA19

Reputation: 580

Writing file for each process of MPI

I have written this part of the code in order to have a file for each rank and see its content. The question I have is that how can I extend this code to work for an arbitrary size. Here, as I was running with 4 cores; I already knew my size so I wrote my code with 4 if conditions which I think there should be a better way to handle this for a higher number of processes.

string local_string = to_string(rank) + base;
ofstream output{ local_string };
if (local_string == "0.txt") {
    for (int i = 0; i < N;i++) {
        output << data[i] << endl; 
    }
}

if (local_string == "1.txt") {
    for (int i = 0; i < N;i++) {
        output <<data[i] << endl;
    }
}

if (local_string == "2.txt") {
    for (int i = 0; i < N;i++) {
        output << data[i] << endl;
    }
}

if (local_string == "3.txt") {
    for (int i = 0; i < N;i++) {
        output << data[i] << endl;
    }
}

Upvotes: 1

Views: 514

Answers (2)

dreamcrash
dreamcrash

Reputation: 51583

Because you are running with multiple processes in parallel you do not actually need to specify the conditions:

string local_string = to_string(rank) + base;
read the file with the name local_string
and print the content of the file to the output

If it for debugging purposes you might to want to add a condition so that you only print the file of the process with a certain rank:

    if(rank == rank_to_print_the_file){
       string local_string = to_string(rank) + base;
       read the file with the name local_string
       and print the content of the file to the output
   }

Upvotes: 1

MA19
MA19

Reputation: 580

Using MPI_Barrier before writing to files will eliminates us to come with the idea of if the condition for each process

Upvotes: 0

Related Questions