2012-02-23 54 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; 
     } 
    } 
} 
相关问题