简体   繁体   中英

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

I am trying to learn C++. I am reading a character file into a character array like below:

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

But this code is slow for reading large char file. Now, how to read a char file in a fast way into a char array ? In Java, I usually use memory mapped buffer. Is it in C++ also. Sorry, I am new in C++.

How to read a char file into a char array:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM