spacedancechimp
spacedancechimp

Reputation: 79

output to file c programming

I have an array of outputs that were generated in a model with a source code file that is linked to it. It is referenced here as

struct nrlmsise_output output[ARRAYLENGTH]; 

in the following function I have written. I'm just trying to put these outputs generated from another function

output[i].d[5]

in a file for me to work with in my Python program. I'll eventually need it to be a csv file in Python, so if anyone knows how to directly make it a .csv that would be awesome, but I haven't found a successful method for that so .txt is fine. Here is what I have so far, when I run the code and the output file I'm getting the format I want, but the numbers in the output are way off. (Values of 10^-100 when I'm working with 10^-9). Can anyone tell why this is happening? Also, I already tried putting the outputs in a separate array and then calling from that array but it didn't work. I may not have done it correctly however, this project is the first time I've had to use C.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "nrlmsise-00.h"

#define ARRAYLENGTH 10
#define ARRAYWIDTH 7

void test_gtd7(void) {
    int i;


    struct nrlmsise_output output[ARRAYLENGTH];
    for (i=0;i<ARRAYLENGTH;i++)
        gtd7(&input[i], &flags, &output[i]);
    for (i=0;i<ARRAYLENGTH;i++) {
        printf("\nRHO   ");
        printf("   %2.3e",output[i].d[5]);
        printf("\n");
    //The output prints accurately with this.
    }
    }

void outfunc(void){

    FILE *fp;
    int i;
    struct nrlmsise_output output[ARRAYLENGTH]; //I may be calling the      output wrong here
    fp=fopen("testoutput.txt","w");
     if(fp == NULL)
        {
        printf("There is no such file as testoutput.txt");
        }
    fprintf(fp,"RHO");
    fprintf(fp,"\n");


    for (i=0;i<ARRAYLENGTH;i++) {

        fprintf(fp, "%E", output[i].d[5]);
        fprintf(fp,"\n");
        }

    fclose(fp);
    printf("\n%s file created","testoutput.txt");
    printf("\n");
    }

Upvotes: 0

Views: 100

Answers (1)

Weather Vane
Weather Vane

Reputation: 34585

Your local variables output are not seen outside of the functions in which they are declared and used. The variables output in each of your two functions are unrelated except by having the same name: they do not hold the same data.

You need to either declare output as a global array, or pass the array to test_gtd7()

void test_gtd7(struct nrlmsise_output *output) {
    ...
}

void outfunc(void) {
    struct nrlmsise_output output[ARRAYLENGTH];
    ...
    test_gtd7(&output);
    ...
}

OR

struct nrlmsise_output output[ARRAYLENGTH];         // gobal array

void test_gtd7() {
    //struct nrlmsise_output output[ARRAYLENGTH];   // remove
    ...
}

void outfunc(void) {
    //struct nrlmsise_output output[ARRAYLENGTH];   // remove
    ...
}

Upvotes: 1

Related Questions