2012-11-09 73 views
0

我想學習C++。我正在將字符文件讀入如下的字符數組中:C++:如何快速讀取字符文件到char數組中?

#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++新手。

+1

內存映射平臺(操作系統)的一部分,所以如果你能在Java中做到這一點,那麼你可以做的在C和C++。儘管如此,取決於你的平臺。另外,「大文件」有多大? –

+0

我很確定C++ _does_提供內存映射文件。 –

+4

請參閱[mmap()](http://linux.die.net/man/2/mmap) – tomahh

回答

1

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

4

如何讀取字符文件轉換成字符數組:文件

#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; 
} 
相關問題