我正在努力学习 C++。我正在将字 rune 件读入字符数组,如下所示:
#include <iostream>
#include <fstream>
#include<conio.h>
#include <stdint.h>
using namespace std;
int main () {
char c, str[256];
ifstream is;
cout << "Enter the name of an existing text file: ";
cin.get (str,256);
is.open (str);
int32_t fileSize = 0;
if(is.is_open())
{
is.seekg(0, ios::end );
fileSize = is.tellg();
}
cout << "file size is " << fileSize << "\n";
is.close() ;
is.open (str);
char chararray [fileSize] ;
for(int i = 0 ; i < fileSize ; i++)
{
c = is.get();
chararray [i] = c ;
}
for(int i = 0 ; i < fileSize ; i++)
{
cout << chararray [i];
}
is.close();
getch();
return 0;
}
但是这段代码对于读取大的字 rune 件来说很慢。现在,如何快速将 char 文件读入 char 数组?在Java中,我通常使用内存映射缓冲区。它也在C++中吗?抱歉,我是 C++ 新手。
最佳答案
如何将一个字 rune 件读入一个字符数组:
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char buffer[256];
long size;
ifstream infile ("test.txt",ifstream::binary);
// get size of file
infile.seekg(0,ifstream::end);
size=infile.tellg();
infile.seekg(0);
//reset buffer to ' '
memset(buffer,32,sizeof(buffer ));
// read file content into buffer
infile.read (buffer,size);
// display buffer
cout<<buffer<<"\n\n";
infile.close();
return 0;
}
关于C++ : how to read a char file in a fast way into a char array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13306854/