2012-02-23 56 views
2

我需要從下面的文件中獲取文件指針的行位置。如何使用fopen打開文件中的當前行?

string1\n 
string2\n 
string3\n 

我正在使用此功能讀取文件。

function get() { 
    $fp = fopen('example.txt', 'r'); 
    if (!$fp) { 
     echo 'Error' . PHP_EOL; 
    } 
    while(!feof($fp)) { 
     $string = trim(fgets($fp)); 
     if(!$string) { 
       continue; 
     } else { 
      /* 
      * Here I want to get a line number in this file 
      */ 
      echo $string . PHP_EOL; 
     } 
    } 
} 
+2

如何爲每個fgets添加一個行計數器? – 2012-02-23 16:49:50

+0

文件將被讀取使用fseek() – NiLL 2012-02-23 16:51:15

+0

我很困惑;你是用'fgets()'來讀取文件還是'fseek()'?如果你使用'fseek()'你能編輯你的問題來反映你實際使用的代碼嗎? – 2012-02-23 16:59:52

回答

2

簡單的解決方案是使用計數器。

function get() { 

    // Line number counter 
    $lncount = 0; 

    $fp = fopen('example.txt', 'r'); 
    if (!$fp) { 
     echo 'Error' . PHP_EOL; 
    } 
    while(!feof($fp)) { 
     $string = trim(fgets($fp)); 

     // Increment line counter 
     $lncount++; 

     if(!$string) { 
     continue; 
     } else { 

     // Show line 
     echo "Current line: " . $lncount; 

     echo $string . PHP_EOL; 
     } 
    } 
} 
相關問題