c - 在 txt 文件中搜索关键字并用 C 记录它
问题描述
我正在尝试使用 C 来搜索包含 C 代码的文件。它旨在搜索整个文件,找到某些关键字或字符(例如查找 Ints、Longs、For 循环等)并通过递增计数器记录它们,以及计算所有代码总行数。然后它意味着提供每个关键字的总数,因此可以根据关键字在文件中出现的频率计算百分比。
但是,我无法让代码识别关键字。我应该如何阅读代码的总行以及查找关键字?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define _CRT_SECURE_NO_WARNINGS
/* Count and compute:
number of total lines
number and percentage of blank lines
number and percentage of comments (start with // or /*)
number and percentages of ints, longs, floats, doubles, char
number and percentages of if's
number and percentage of else's
number and percentage of for's
number and percentage of switch
number and percentage of semicolons
number and percentage of structs
number and percentage of arrays (contains [ or ], divide count by 2)
number of blocks (contains { or }, divide count by 2)
*/
int main(void)
{
int lineCount = 0; // Line counter (result)
int forCount = 0; // For counter
int intCount = 0;
char c;
FILE *ptr_file;
char buf[1000];
ptr_file = fopen("file.txt", "r");
if (!ptr_file)
return 1;
while (fgets(buf, 1000, ptr_file) != NULL) {
for (c = getc(ptr_file); c != EOF; c = getc(ptr_file)) {
if (c == '\n') // Increment count if this character is newline
lineCount = lineCount + 1;
}
}
fclose(ptr_file);
//End of first scan
ptr_file = fopen("file.txt", "r");
if (!ptr_file)
return 1;
while (fgets(buf, 1000, ptr_file) != NULL) {
for (c = getc(ptr_file); c != EOF; c = getc(ptr_file)) {
if (c == 'for') // Increment count if this character is for
forCount = forCount + 1;
}
}
fclose(ptr_file);
//End of second scan
ptr_file = fopen("file.txt", "r");
if (!ptr_file)
return 1;
while (fgets(buf, 1000, ptr_file) != NULL) {
for (c = getc(ptr_file); c != EOF; c = getc(ptr_file)) {
if (c == 'int') // Increment count if this character is for
intCount = intCount + 1;
}
}
fclose(ptr_file);
printf("\nThe file has %d lines\n", lineCount);
printf("\nThe file has %d fors\n", forCount);
printf("\nThe file has %d ints\n", intCount);
}
解决方案
推荐阅读
- pytorch - Tensorboard 在训练期间无法绘制所有时期的模型权重
- sql - 使用 JOIN 显示 MAX 记录
- amazon-web-services - 多区域访问 AWS CLI
- c# - 在 ASP.NET Core Web API 中为生产环境设置 launchurl
- django - 我如何将 django url 参数传递给重定向功能
- regex - 过滤 4 个大写字母
- flutter - graphql_flutter - 从 pub.dev 页面复制代码 - 仍然出现错误
- javascript - 未捕获的 SyntaxError:标识符“myOptions”已在 JavaScript 中声明
- pine-script - 每次 MACD 研究中的直方图会出现更高的低点时发出警报,反之亦然
- apache-kafka - 如何在 kafka 消费者中消费和解析不同的 Avro 消息