簡體   English   中英

在C中的文件中找到最長的注釋行

[英]Find longest comment line in a file in C

所以我有此功能來查找文件中最長的行:

int LongestLine(FILE *filename) {

  char buf[MAX_LINE_LENGTH] = {0};

  char line_val[MAX_LINE_LENGTH] = {0};
  int line_len = -1;
  int line_num = -1;
  int cur_line = 1;

  filename = fopen(filename, "r");

  while(fgets(buf, MAX_LINE_LENGTH, filename) != NULL) {
    int len_tmp = strlen(buf) - 1;

    if(buf[len_tmp] == '\n')
      buf[len_tmp] = '\0';

    if(line_len < len_tmp) {
      strncpy(line_val, buf, len_tmp + 1);
      line_len = len_tmp;
      line_num = cur_line;
    }

    cur_line++;
  }

  return line_num;
}

而我當時正在考慮將其與這一組合:

bool startsWith(const char *pre, const char *str)
{
    size_t lenpre = strlen(pre),
           lenstr = strlen(str);
    return lenstr < lenpre ? false : strncmp(pre, str, lenpre) == 0;
}

但是..但是, LongestLine()函數返回一個整數。 那么,如何使用這兩個函數,以便可以找到以//開頭的最長行?

if語句中添加對startsWith (以查看是否為注釋)的調用,以決定行是否是最長的新行:

if( startsWith("//",buf) && (line_len < len_tmp) ) { 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM