c - 在C中查找文件中最长的注释行

标签 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) ) { 

关于c - 在C中查找文件中最长的注释行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27990971/

相关文章:

c - 随机数生成器 PCG 库。如何生成在一定范围内设置的 float 。 C语言工作示例

c++ - 在C中使用utf8字符串

c - 视频和音频都尽可能快地运行 - ffmpeg

c - 如何在 C 中将 char *string 复制到 char c[]?

c - 尝试覆盖 'fopen()' 但 GCC 给出 "error: conflicting types for ' fopen'"

c - 为什么数组接收的值可以超过它声明的值

编译 OpenGL 和 GLUT OSX

c - 双向链表

c++ - printf 的 "precision"说明符的类型是什么?

c - 将变量传递给 popen 命令