2014-09-20 40 views
-4

2.6 GB,32位有符號整數的二進制文件,每行有100個元素。如何讀取Python,C或Java中的大數據文件的一部分?

我可以逐行讀取在Java中有:

DataInputStream dis = new DataInputStream(new FileInputStream("input.rawdata")) 
for(int i = 0; i < 100; i++){ 
    int idata = dis.readInt(); 
    % DO THE NECESSARY TO LOAD idata IN A VARIABLE ARRAY % 
} 
dis.close(); 

但是,如果我想只讀第505行不讀最初的504線,那該怎麼辦呢?

或者如果數據是100 x 1000矩陣並且希望只讀取第15行至第80行的矩形&第100至第200列。那麼如何用上述三種語言中的任何一種來實現(最好是Python & Java)。

與代碼效率相關的建議非常受歡迎。

+1

我想你想要MMAP? – vaultah 2014-09-20 07:02:42

+3

閱讀'fseek()'並從中取出它。 – NPE 2014-09-20 07:14:13

+0

二進制文件中行的含義是什麼? – 2014-09-20 09:12:03

回答

0

在C,只要你知道字節的文件的大小,是這樣的:

#define FILESIZE [file size in bytes] 
#define NUMROWS [number of rows] 
#define NUMCOLS [number of columns] 
#define cnk_size(X,Y) (X*Y) 
#define ENDROW [desired ending row] 
#define SRTROW [desired starting row] 
#define ENDCOL [desired ending col] 
#define SRTCOL [desired starting col] 


void* data = malloc(FILESIZE*sizeof(unsigned char)); 
fgets((char*)data,FILESIZE,stdin); 

void* chunk = malloc(sizeof(unsigned char)*cnk_size(ENDROW-SRTROW,ENDCOL-SRTCOL)); 

register i = SRTROW; 
register j = SRTCOL; 

register datptr = (unsigned int)data; 
register cnkptr = (unsigned int)cnkptr; 

for(i = SRTROW; i < ENDROW; i++) 
    for(j = SRTCOL; j < ENDCOL; j++) 
     *((char*)cnkptr++) = *((char*)(datptr + i*NUMCOL + j)); 

在速度方面可能可以刪除for循環進行優化,但你沒有得到比這個快得多,並且java/python可能不會靠近。 (你最可能用fgets()門控)。 要將文件傳遞給程序:

bash -$$ .\your-program-name < your-file-name 

如果你不希望加載整個文件到內存中,查找分割調用: https://www.gnu.org/software/coreutils/manual/html_node/split-invocation.html 來源:我的生鏽的池分配。