C Martinez
C Martinez

Reputation: 1

Creating and writing in multiple txt files in C

I've got a code which creates j files (Node[j].ID) in a directory called (Nodes) and in those j files the code writes the info contained in NodeResults. At the moment the code doesn't neither create nor write in files because of the strcat function doesn't work. Please any idea how to correct the code in order to get the created files with the info contained in NodeResults on it?. Thanks in advance. Please find the code below:

{

    int period, j ;
    FILE*temporal;
    FILE* temp_time;
    char path[25];
    char* extention = ".txt";
    char s[30];
    char temporal2[25];
    long time_val = 0;
    _mkdir("Nodes");
    _mkdir("time"); 


    temp_time = fopen("Time/time.txt", "w");
    fprintf(temp_time, "%d,%d\n", ReportStep, Nperiods);
    fclose(temp_time);

    for ( j = 0; j < Nobjects[NODE]; j++ ) {
        /* File path writing */

        strcpy(temporal2,"Nodes/");
        strcat(temporal2, Node[j].ID);
        strcat(temporal2, extention);

        temporal= fopen(temporal2, "w"); 
    }                    
    for ( period = 1; period <= Nperiods; period++ ) {
        output_readNodeResults(period, j);
        fprintf(temporal, "%9.3f,%9.3f,%9.3f,%9.3f,%9.3f\n",
                    NodeResults[NODE_INFLOW],
                    NodeResults[NODE_OVERFLOW], 
                    NodeResults[NODE_DEPTH],
                    //NodeResults[NODE_HEAD],
                    NodeResults[NODE_VOLUME]);
    }
    fclose(temporal);

    return Nperiods;
}

Upvotes: 0

Views: 361

Answers (2)

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

I have properly formatted your code, and now John's comment immediately sticks out: the brace is on the wrong line, resulting in wrong for loops and blocks!

Should you have formatted the code properly yourself, you would have seen it immediately yourself!

Upvotes: 1

John Bollinger
John Bollinger

Reputation: 180306

You open a bunch of files in the first for loop, but do not write anything to them. At each iteration, you assign a new FILE * to variable temporal, overwriting any previous value. Afterward, in your second for loop you write a bunch of output to the last file opened -- the one to which temporal refers at that point.

It looks like you want to move the body of the second for loop and the fclose() into the first for loop.

Upvotes: 4

Related Questions