在 C 中的 fprintf 上保存具有不同名称的多个文件

Save multiple files with different names on fprintf in C

我想保存多个 .dat 文件但出现警告:"format ‘%f’ expects argument of type ‘double’, but argument 3 has type ‘double *’ [-Wformat=]" 并且文件为空。

FILE *f1;
double hist[N];
double delta_t = 0.25;
int n_periodos = 0;
char name[100]; 
sprintf(name,"testeT%f.dat",n_periodos*delta_t);
f1 = fopen (name,"w");
fprintf(f1,"%lf",hist); //The problem is here

当您调用运行时函数时,重要的是检查 return 值以查看它们是否成功。

要记住的另一件事是浮点数和双精度数不是精确值,因此将它们用作文件名的一部分并不好。

所以检查 return 值

f1 = fopen(name, "w");
if (f1 != NULL)
{
  ...
  fclose(f1);
}
else
{
  perror(name); // or write out the error
}

另请注意,如果您在函数中声明它们,则声明的变量不是必需的 0,它们可以具有任意值,因此您需要对其进行初始化

double hist[N] = {0};

当您将 hist[] 写入文件时,您不能那样使用 fprintf,您应该遍历这些值,一次写入一个值,fprintf 无法处理像您所写的那样写入数组。

for (int i = 0; i < N; ++i)
{
  fprintf(f1, "%lf\n", hist[i]); // added \n as delimiter
}

hist 是一个双精度数组(或者技术上是一个指针,double*,因为它传递给 fprintf),但是您试图将单个双精度值写入文件,而不是数组.你可能想要这样的东西来写整个数组:

for (int i = 0; i < N; i++)
{
    fprintf(f1, "%f", hist[i]);
}

或者只有一个值:

fprintf(f1, "%f", hist[0]);

此外,在您的示例代码中,hist 是一个未初始化的数组。写入文件的内容可能不是您所期望的。

你在最后一行的问题是你将 hist(这是一个 double 的数组)传递给 fprintf 你使用了 %lf 转换说明符,它需要一个 double 作为它的参数(不是一个 double 数组)

当您在 C 中声明一个数组时,在访问时,该数组将转换为指向数组 C11 Standard - 6.3.2.1 Lvalues, arrays, and function designators(p3) 中第一个元素的指针。 (例外情况在此处说明——当与 sizeof_Alignof 一起使用时,或与一元运算符 & 一起使用时,或当使用 字符串文字[=49= 初始化时]) None 的应用在这里。

所以你的声明:

double hist[N];

hist是double的数组。当您在以下位置使用 hist 时:

fprintf (f1, "%lf", hist);

hist 被转换为指向数组中第一个元素的指针(例如, 第一个元素的 地址),其类型为 'double*' .要解决此问题,您需要 取消引用 指针(通常通过在变量后面使用 [element] 来完成数组,例如

fprintf (f1, "%lf", hist[0]);  /* or element 1, 2, 3, .... */

这将使您的类型保持一致。

您可以重写您的代码(认为仍然不清楚 N 是什么),以消除问题并纠正其他一些缺点(在下面的评论中指出)

#include <stdio.h>

#define MAXC  100   /* if you need a constant, #define on (or more) */
#define NHIST  32   /* it is unclear where N came from in your code */

int main (void) {

    FILE *f1 = NULL;            /* initialize all variables and help */
    double hist[NHIST] = {0.0}; /* avoid Undefined Behavior :)       */
    double delta_t = 0.25;
    int n_periodos = 0;
    char name[MAXC] = ""; 

    /* use snprintf to protect the bounds of 'name' */
    snprintf (name, MAXC - 1, "testeT%f.dat", n_periodos*delta_t);

    f1 = fopen (name, "w");     /* call fopen */
    if (f1 == NULL) {           /* validate file is open for writing */
        perror ("fopen-name");
        return 1;
    }

    fprintf (f1, "%lf", hist[0]);
}

检查一下,如果您还有其他问题,请告诉我。

关于:

fprintf(f1,"%lf",hist);

在 C 中,对数组名称的引用 'degrades' 对数组第一个字节的地址。

更好用:

fprintf(f1,"%lf",hist[0]);

因为这将输出数组中第一个条目的内容。