Search code examples
c++parallel-processingoutputmpihpc

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;
    }
}

Solution

  • 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
       }