2016-02-11 23 views
-1

我寫了一些代碼,從二進制文件中讀取第一個pos字節並將其寫入另一個文件。原來我運行時出現了分段錯誤。這裏是代碼:C - 分段錯誤(內核轉儲),從文件中讀取前N個字節

void outputUntillPos(const char * inFileName, const char * outFileName, int pos) { 
FILE * inFile = fopen(inFileName, "r"); 
FILE * outFile = fopen(outFileName, "aw"); 

char buf[1024]; 
int read = 0; 
int remain = pos; 

do { 
    if(remain <= 1024) { 
     read = fread(buf, 1, pos, inFile); 
    } else { 
     read = fread(buf, 1, 1024, inFile); 
    } 

    remain -= read; 
    fwrite(buf, 1, read, outFile); 
    memset(buf, 0, 1024); 
} while(remain > 0); 
} 

我在這裏是否超出範圍操作?

編輯:感謝所有的幫助,這裏是編輯的代碼。

void outputUntillPos(const char * inFileName, const char * outFileName, int pos) { 
FILE * inFile = fopen(inFileName, "r"); 
FILE * outFile = fopen(outFileName, "aw"); 

char buf[1024]; 
int read = 0; 
int remain = pos; 

if((inFile != NULL) && (outFile != NULL)) { 
    do { 
     if(remain <= 1024) { 
      read = fread(buf, 1, remain, inFile); 
     } else { 
      read = fread(buf, 1, 1024, inFile); 
     } 

     remain -= read; 
     fwrite(buf, 1, read, outFile); 
     memset(buf, 0, 1024); 
    } while(remain > 0 && read > 0); 
} 

fclose(inFile); 
fclose(outFile); 
} 
+0

如果你關閉它們,你在哪裏關閉這些文件? – Jacobr365

+3

第1步。您沒有檢查打開的文件。如果他們不這樣做肯定會出現段錯誤。 –

+1

當讀取的剩餘字節數量(在變量'remaining'中)變得小於'1024'時,由於某種原因你試圖讀取'pos'字節。爲什麼'pos'?你應該在最後一次迭代中讀取「剩餘」字節。 – AnT

回答

0

remain成爲< = 1024和輸入塊的if部分,你在pos字節,如果是大於1024會寫了緩衝區的到底是哪讀書。這就是導致段錯誤的原因。

您想在這裏使用remain代替:

if(remain <= 1024) { 
    read = fread(buf, 1, remain, inFile); 
} else { 
    read = fread(buf, 1, 1024, inFile); 
} 

此外,一定要檢查的fopen返回值,並fclose(inFile)fclose(outFile)你回來之前。

0

當需要讀取的字節的剩餘量(變量remain)變得小於1024時,出於某種原因,您嘗試讀取pos字節。爲什麼pos ???您應該在最後一次迭代中讀取remain字節,而不是pos字節。

如果pos大於1024並且輸入文件仍然有額外數據,那麼您當然會在最後一次迭代時溢出緩衝區。