2

刚开始使用 Openmpi。尝试将整数写入和读取文件..用于写入的代码:

写入文件的字符无法识别,主要是垃圾。

#include <stdlib.h>
#include <stdio.h>
#include "mpi.h"

#define BUFSIZE 10
#define FIRSTCHAR 1
#define FILENAME "file1.dat"

int main(int argc, char* argv[]) {
  int i, np, me;
  int buf[BUFSIZE];     /* The buffer to write */
  MPI_File myfile;       /* Shared file */

  /* Initialize MPI */
  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &me);
  MPI_Comm_size(MPI_COMM_WORLD, &np);

  /* Initialize buf with characters. Process 0 uses 'a', process 1 'b', etc. */
  for (i=0; i<BUFSIZE; i++) {
    buf[i] = FIRSTCHAR+(me);
  }

  /* Open the file */
  MPI_File_open (MPI_COMM_WORLD, FILENAME, MPI_MODE_CREATE | MPI_MODE_WRONLY,
         MPI_INFO_NULL, &myfile);
  /* Set the file view */
  MPI_File_set_view(myfile, me*BUFSIZE*sizeof(int), MPI_INT, MPI_INT, 
            "native", MPI_INFO_NULL);
  /* Write buf to the file */
  MPI_File_write(myfile, buf, BUFSIZE*sizeof(int), MPI_INT, MPI_STATUS_IGNORE);
  /* Close the file */
  MPI_File_close(&myfile);
  MPI_Finalize();
  exit(0);
}

不工作..请帮助!

4

3 回答 3

6

写入的文件不是垃圾,它们只是二进制文件

如果你在 linux

首先备份你的文件

cp file file2

然后

尝试使用此命令从二进制转换为 ascii

hexdump -v -e '7/4 "%10d "' -e '"\n"' file2

还有一个旁注:除非您将数百万行写入文件,否则您甚至可能不需要 mpi_file 写入/加载函数

于 2012-07-06T05:09:42.930 回答
1

s以int二进制模式写入文件,即它们不会像使用屏幕输出那样转换为字符串和打印printf,而是以某种方式将它们的内存表示复制到文件中。如果您编写代码从文件中读取它们(使用MPI_File_read),它将正常工作。

请注意,您自己阅读二进制格式可能非常棘手,因为 MPI 试图跨平台并且可能会写入一些额外的类型信息,因此您应该使用 MPI 从这些文件中读取。

于 2012-07-06T03:32:34.883 回答
1

这是一个更简洁的命令,可以在 Linux 上以 ascii 格式查看二进制文件:按照 pyCthon 的建议备份文件:

cp file temp

然后,运行以下命令将文件打印为 ascii 字符:

od -c temp

如果您的数据恰好是整数:

od -i temp
于 2019-03-19T05:52:33.097 回答