C ++:如何快速将char文件读入char数组?

时间:2012-11-09 11:02:27

标签: c++

我正在尝试学习C ++。我正在将字符文件读入如下字符数组:

#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;
}

但是这段代码读取大型char文件的速度很慢。现在,如何快速将char文件读入char数组?在Java中,我通常使用内存映射缓冲区。它是否也在C ++中。对不起,我是C ++新手。

2 个答案:

答案 0 :(得分:4)

如何将char文件读入char数组:

#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;
}

答案 1 :(得分:1)

您可以使用is.read(chararray,fileSize)。