2016-05-26 77 views
0

我正在開發一個文本採集引擎,它使用fwrite()來編寫文本,但我想在寫入過程中放置​​一個1.5 MB的文件大小上限,所以如果文件大於1.5 mb它會從停止的地方開始寫一個新的文件,直到它將源文件的內容寫入多個文件。我有谷歌搜索,但很多教程和例子對我來說太複雜,因爲我是一個新手程序員。下面的代碼位於for循環內,該循環提取文本($RemoveTwo)。它不起作用,因爲我需要。任何幫助,將不勝感激。將大文本文檔分割爲多個較小的文本文件

 switch ($FileSizeCounter) { 
      case ($FileSizeCounter> 1500000): 
       $myFile2 = 'C:\TextCollector/'.'FilenameA'.'.txt'; 
       $fh2 = fopen($myFile2, 'a') or die("can't open file"); 
        fwrite($fh2, $RemoveTwo); 
        fclose($fh2); 
       break; 
      case ($FileSizeCounter> 3000000): 
       $myFile3 = 'C:\TextCollector/'.'FilenameB'.'.txt'; 
       $fh3 = fopen($myFile3, 'a') or die("can't open file"); 
        fwrite($fh3, $RemoveTwo); 
        fclose($fh3); 
       break; 
      default: 
       echo "continue and continue until it stops by the user"; 
     } 
+0

你應該包含之前使用第一個文件獲得更完整答案的代碼。 –

+0

我補充說明@ julie –

回答

0

試着做這樣的事情。您需要從源代碼讀取,然後一塊一塊地檢查源文件的結尾。當你比較max和緩衝值,如果它們是true,然後關閉當前文件並打開一個新的帶有自動遞增的數字:

/* 
** @param $filename [string] This is the source 
** @param $toFile [string] This is the base name for the destination file & path 
** @param $chunk [num] This is the max file size based on MB so 1.5 is 1.5MB 
*/ 
function breakDownFile($filename,$toFile,$chunk = 1) 
    { 
     // Take the MB value and convert it into KB 
     $chunk  = ($chunk*1024); 
     // Get the file size of the source, divide by kb 
     $length  = filesize($filename)/1024; 
     // Put a max in bits 
     $max  = $chunk*1000; 
     // Start value for naming the files incrementally 
     $i   = 1; 
     // Open *for reading* the source file 
     $r   = fopen($filename,'r'); 
     // Create a new file for writing, use the increment value 
     $w   = fopen($toFile.$i.'.txt','w'); 
     // Loop through the file as long as the file is readable 
     while(!feof($r)) { 
      // Read file but only to the max file size value set 
      $buffer = fread($r, $max); 
      // Write to disk using buffer as a guide 
      fwrite($w, $buffer); 
      // Check the bit size of the buffer to see if it's 
      // same or larger than limit 
      if(strlen($buffer) >= $max) { 
       // Close the file 
       fclose($w); 
       // Add 1 to our $i file 
       $i++; 
       // Start a new file with the new name 
       $w = fopen($toFile.$i.'.txt','w'); 
      } 
     } 
     // When done the loop, close the writeable file 
     fclose($w); 
     // When done loop close readable 
     fclose($r); 
    } 

使用方法:

breakDownFile(__DIR__.'/test.txt',__DIR__.'/tofile',1.5); 
+0

謝謝@Rasclatt,但對我來說這很難理解 –

+0

不太確定告訴你什麼。沒有更簡單的方法來做到這一點,更人性化。您打開一個源文件,然後啓動一個目標文件,然後循環執行源代碼檢查,以查看文件是否已完成讀取,而您正在寫入目標文件。一旦循環達到讀取的最大文件大小,它將關閉目標文件,並從停止的位置開始一個新文件。它會增加'$ i'變量,以便文件逐步編號。它重複循環直到完成讀取文件。 – Rasclatt

相關問題