C++ : how to read a char file in a fast way into a char array?

标签 c++

我正在努力学习 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/

相关文章:

c++ - 没有页面文件的 Windows XP 内存管理 - 后果是什么。堆碎片?

c++ - 在以下情况下,集合插入如何工作?

c++ - 我应该停止使用抽象基类/接口(interface),而是使用 boost::function/std::function 吗?

c++ - 如何关闭程序中用于打印调试数据的功能

c++ - 将返回 void 但具有整数参数的函数作为 ARGUMENT 本身传递给另一个函数

c++ - 在 C++ 项目中维护版本的好方法是什么?

c++ - CPaneDialog控件背景(文字控件)

c++ - 使用字符串流解析字符串时,它会提取换行符

c++ - std::numeric_limits<T>::digits 应该代表什么?

c++ - 如何在不暴露类细节的情况下传递函数指针