【问题标题】:output to file c programming输出到文件 c 编程
【发布时间】:2015-03-30 18:52:39
【问题描述】:

我有一个在模型中生成的输出数组,其中有一个链接到它的源代码文件。此处引用为

struct nrlmsise_output output[ARRAYLENGTH]; 

在我编写的以下函数中。我只是想把这些输出从另一个函数生成

output[i].d[5]

在我的 Python 程序中使用的文件中。我最终需要它成为 Python 中的 csv 文件,所以如果有人知道如何直接将其制作为 .csv 会很棒,但我还没有找到成功的方法,所以 .txt 很好。到目前为止,这是我所拥有的,当我运行代码和输出文件时,我得到了我想要的格式,但是输出中的数字很差。 (当我使用 10^-9 时,值为 10^-100)。谁能说出为什么会这样?另外,我已经尝试将输出放在一个单独的数组中,然后从该数组调用,但它不起作用。我可能做得不对,但是这个项目是我第一次不得不使用 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");
    }

【问题讨论】:

  • 以及在生成输出的函数中,输出结构被这样调用struct nrlmsise_output output[ARRAYLENGTH];for (i=0;i&lt;ARRAYLENGTH;i++){ gtd7(&amp;input[i], &amp;flags, &amp;output[i]);,我只使用了1个输出变量(output[i].d[5])。
  • 请包含struct nrlmsise_output的定义
  • 是的,包括结构定义并编辑您的帖子,而不是向 cmets 添加新代码
  • 那在哪里?也有人提出并删除了一条评论,询问output 是如何填充的,您对此发表了评论,而不是显示完整的功能。 output 是一个局部变量,所以说你在其他地方(例如在评论中)填写它是没有意义的。代码fprintf(fp, "%E", output[i].d[5]); 中只有一个相关行,但你什么也没告诉我们,除非它不起作用。
  • “没有像 testoutput.txt 这样的文件”不是有用的错误消息。尝试:char *path="testoutput.txt"; fp = fopen(path,"w"); if(fp == NULL) {perror(path); exit(EXIT_FAILURE);} 2 个主要好处:它告诉您为什么 fopen 失败,并在正确的流上打印错误消息。 (错误不属于标准输出)。

标签: c file struct output


【解决方案1】:

您的局部变量output 在声明和使用它们的函数之外是看不到的。这两个函数中的变量output 是不相关的,除非它们具有相同的名称:它们不包含相同的数据。

您需要将output 声明为全局数组,或者将数组传递给test_gtd7()

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

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

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

【讨论】:

  • 在第一个选项中,您可能需要编辑访问作为参数传递的数组的方式,可惜我没有进入它。
  • 哦,不,我在那个函数中有其他结构要调用,我只是把它们放在了这里,这就是为什么我认为哈哈。
猜你喜欢
  • 1970-01-01
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 2021-01-22
  • 2011-07-05
  • 1970-01-01
  • 1970-01-01
  • 2018-05-04
相关资源
最近更新 更多