检测存储在字符串变量中的文件中的行尾

Detecting end of the line in file stored in string variable

这是我碰巧通过php分析的文件:

#include <stdio.h>
#include <stdlib.h>
#include "subdir/file.h"

#define STRUCT_PTR struct {int i;} *

// This function does nothing useful.
int func(int i, ...) {
    return i + i;
}

/*
    + + + + + + Main. + + + + + + + + +
*/
int main(void) {
    int i = 1;
    char s[10] = "- - - -";

    i++;
    s[1] = 'b';
    i += func(4);

    STRUCT_PTR t = malloc(sizeof(*t));
    if (!t) {
        return EXIT_FAILURE;
    }
    t->i = 1 == 2 ? 3 : -5;

    return EXIT_SUCCESS;
}

// zZ

在最后一行注释之后是文件结尾。相应地,当我用和编辑器打开它时,评论之后没有新的空行。

我把这个文件的内容存到变量里,像这样$var = file_get_contents(path-to-file.c).

然后我循环它:

for($i = 0; isset($fileContent[$i]); $i++)

我计算评论中的字符数,包括 "//", "/*", "*/",我也计算行尾字符。 预期结果是 89,但我仍然只得到 88。我很确定这是因为我无法检测到行尾,因为后面没有新行。

我是这样测试的if($fileContent[$i]==PHP_EOL),但我也尝试过使用\n、\r\n等不同的组合

提前感谢您的帮助!

编辑: 更多我的代码

for($i = 0; isset($fileContent[$i]); $i++)
                {

// ... some not so important conditions


                    if($fileContent[$i] == '/' && !$inComment && !$inBComment)
                    {
                        if($fileContent[$i+1] == '/')
                        {
                            $inComment = true;
                            $charCount += 2;
                            $skip = true;
                            continue;
                        }
                    }

                    if($inComment)
                    {

                        if($fileContent[$i] == PHP_EOL)
                        {
                            $charCount++;
                            $inComment = false; 
                        }
                        else
                        {
                            $charCount++;
                        }

                        continue; 

                    }

您不需要遍历每一行的内容来执行此操作。这个班轮应该为你做。请注意,这仅对一行注释有效。

<?php

//load file into array
$fileContents = file('test.txt');

//init counter
$charCount = 0;

foreach ($fileContents as $fileContent)
{
    //+count
    $charCount +=  (strpos(trim($fileContent),'//') === 0 )?strlen($fileContent):0;
}

//print
echo $charCount;

?>