MPI:写入和读取整数到文件

问题描述 投票:2回答:3

刚开始使用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);
}

不工作..请帮忙!

c multiprocessing mpi openmpi
3个回答
6
投票

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

如果你的Linux

首先备份你的文件

cp file file2

然后

尝试此命令将二进制转换为ascii

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

另外还有一个注意事项:除非你写入数百万行文件,否则你甚至可能不需要mpi_file写入/加载功能


1
投票

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

请注意,二进制格式可能非常难以自行阅读,因为MPI尝试跨平台并且可能会写一些其他类型信息,因此您应该使用MPI从这些文件中读取。


0
投票

这是一个更简洁的命令,用于在ascii中查看二进制文件。在Linux上:备份文件,如pyCthon建议:

cp file temp

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

od -c temp

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

od -i temp
© www.soinside.com 2019 - 2024. All rights reserved.