簡體   English   中英

C ++:如何以快速方式將char文件讀入char數組?

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

我正在嘗試學習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 ++的新手。

如何將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;
}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM