用 C 编写多个文件并迭代它们的名称 [英] write multiple files in C iterating over their names

查看:46
本文介绍了用 C 编写多个文件并迭代它们的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过迭代、进行一些计算并将索引添加到文件名中来编写一堆文件,这是我的代码的一部分(我强调了代码停止编译的位置):

I am trying to write a bunch of files by iterating, doing some calculations and adding the index to the file's name, heres part of my code (I emphasized where the code stops compiling):

float AltAzCalc(int d, float t, float Lon, float RA, float Dec, float Lat){

    FILE *in;


    -----> char filename[30] = ("hiparcos_horizontal_%lf_%lf.csv",Lon,Lat);
    in = fopen(filename, "w");
    float PI = 3.14159265;// pi
    float G = 6.5949997; 
    float Alt , Az;
    float GST = G + 0.0657098244*d + 1.00273791*t;
    if (GST > 24){
        GST = GST - 24;
    }
    float LST = GST*360/24 + Lon;

    Alt = (180/PI)*(asin(sin(PI*Dec/180)*sin(PI*Lat/180) + cos(PI*Dec/180)*cos(PI*Lat/180)*cos(PI*(LST-RA*360/24)/180)));

    if(sin(PI*(LST-RA*360/24)/180) <= 0){
        Az = (180/PI)*(acos((sin(PI*Dec/180)-(sin(PI*Alt/180)*sin(PI*Lat/180)))/(cos(PI*Alt/180)*cos(PI*Lat/180))));
    }else{
        Az = 360 - (180/PI)*(acos((sin(PI*Dec/180)-(sin(PI*Alt/180)*sin(PI*Lat/180)))/(cos(PI*Alt/180)*cos(PI*Lat/180))));
    }   

    fprintf(in," %lf %lf \n",Alt,Az);

}
int main{
for(int i = -180 ; i < 181 ; i++){
        for(int j = -180 ; j < 181 ; j++){ 
            for(int k = 0; k < 119616 ; k++){

                AltAzCalc(97,9.2,i,AscensionRecta.array[k],Declinacion.array[k],j);



            }

         }
    }
}

我之前使用过这样的语法,只是没有添加任何我想更改的额外数字,这是一个字符串文字,这就是它的要求,知道如何解决这个问题吗?

I have used such syntaxes before only not adding any extra numbers that I want to change, which is a string literal and that's what its asking for, any idea how to fix this?

推荐答案

两件大事:

  1. char filename[30] 的维度可能太小,无法容纳名称.
  2. 你需要使用 sprintf()/snprintf() 生成文件名.
  1. char filename[30] is probably too small in dimension to hold the name.
  2. You need to use sprintf()/snprintf() to generate the filename.

值得一提的是,%f 就足够了,推荐打印一个浮点值.

Worthy to mention, %f is enough and recommended to print a float value.

做一些类似(伪代码)的事情

Do something like (pseudo-code)

char filename[128] = {0};                                   //allocate enough memory
sprintf(filename, "hiparcos_horizontal_%f_%f.csv",Lon,Lat)); //Added missing semi-colon // use %f, that's enough and recommended, too.

注意:在使用返回的文件指针之前,一定要检查fopen()的返回值是否成功.

Note: Always check the return value of fopen() for success before using the returned file pointer.

这篇关于用 C 编写多个文件并迭代它们的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆