我想使用mpich读取文件并计算文件中的字符数。如何使用C语言中的MPI例程来做到这一点。
我尝试使用以下源代码,但我不知道如何进一步进行。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "mpi.h"
int main(int argc, char* argv[])
{
int rank,size;
MPI_File file_handle;
MPI_Init( &argc, &argv );
MPI_Comm_size( MPI_COMM_WORLD, &size );
MPI_Comm_rank( MPI_COMM_WORLD, &rank );
MPI_File_open(MPI_COMM_WORLD, "new.txt",
MPI_MODE_CREATE | MPI_MODE_RDONLY,
MPI_INFO_NULL, &file_handle);
MPI_Offset pos;
MPI_File_seek(file_handle, 0, MPI_SEEK_END);
MPI_File_get_position(file_handle, &pos);
printf ("number of characters = %lld\n", pos);
MPI_File_seek(file_handle, 0, MPI_SEEK_SET);
MPI_File_close(&file_handle);
MPI_Finalize();
}
答案 0 :(得分:0)
您可以使用以下功能将文件处理程序定位到文件的末尾:
MPI_File_seek(file_handle, 0, MPI_SEEK_END)
然后检查您的当前位置:
MPI_Offset pos;
MPI_File_get_position(file_handle, &pos);
printf ("length = %lld\n", pos);
如果您打算读取文件,请不要忘记将file_handler带回到文件的开头
MPI_File_seek(file_handle, 0, MPI_SEEK_SET)
这将计算不可见字符,并将在多个字节上定义的字符计算为多个字符,因此,如果您认为很重要,则可能需要考虑字符集。