【问题标题】:How to save a matrix of type double in a file如何将double类型的矩阵保存在文件中
【发布时间】:2018-10-16 07:14:23
【问题描述】:

我需要生成一个双精度(字典)类型的随机矩阵并将其保存到一个文件中,以便稍后在另一个程序中读取它们。这是我生成数据的方式:(好的,我已经进行了最后一次编辑,现在每个元素在循环中生成后都保存到文件中。但是有一个关于 fopen 不安全的错误!)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>

/* Number of columns and rows in dictionary */
#define M (2000)
#define N ((int)(M/2))

/* Sign function */
double sign(double x) { return (x >= 0) - (x<0); }

/* Matrix indexing convention */
#define id(m, n, ld) (((n) * (ld) + (m)))


FILE *out_file = fopen("name_of_file", "w"); // write only

int main()
{
    double *D;
    double norm = sqrt(N), a;
    int MN = M*N, m, n;

    /* Initialize srand */
    srand(time(NULL));

    /* Initialize dictionary */
    D = (double*)malloc(MN * sizeof(D[0]));
    if (D == 0)
    {
        fprintf(stderr, "!host memory allocation error(dictionary)\n");
        return EXIT_FAILURE;
    }
    for (n = 0; n < N; n++)
    {
        for (m = 0; m < M; m++)
        {
            a = sign(2.0*rand() / (double)RAND_MAX - 1.0) / norm;
            D[id(m, n, M)] = a;
            fprintf(out_file, "%lf ", D[id(m, n, M)]);
        }
    }
}

如何将D 保存在一个文件中,以便稍后在另一个程序中加载它以进行优化?我正在使用 Visual Studio 2017。

【问题讨论】:

  • 为什么要标记 C++?您没有使用它,这是普通的 C。另外,请下次正确格式化您的代码。您的主要签名后缺少{
  • 您的程序无法编译。 id 是什么?
  • 请修正您的代码!我编辑了一次,你又编辑了一遍。现在轮到你了。
  • 基本上有 2 个选项:fwrite()fprintf()。第一个是人类无法读取的,如果复制到不同的系统可能会失败,第二个是人类可读的。

标签: c dataset


【解决方案1】:

定义一个 FILE 类型的指针,它接受一个字符串(文件名)和类型模式(w=write、a=append、r=read)。 遍历矩阵并使用 fprintf

FILE *out_file = fopen("name_of_file", "w"); // write only

for (n = 0; n < N; n++)
{
    for (m = 0; m < M; m++)
    {
        fprintf(out_file,"%lf ", D[n][m]);
    }
}

【讨论】:

  • 感谢您的回答,我需要在定义指针之前创建文件吗?而且我也收到 fopen 不安全的错误!
  • 好的,我已经进行了最后一次编辑,现在每个元素在循环中生成后都保存到文件中。但是有一个关于 fopen 不安全的错误!
  • 不,您之前不需要创建文件。使用操作员编写函数会自动创建它。关于不安全,这取决于您使用的编辑器。使用visual studio,有可能使用fprinf_s
猜你喜欢
  • 2019-09-30
  • 1970-01-01
  • 1970-01-01
  • 2012-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-05
  • 1970-01-01
相关资源
最近更新 更多