我正在尝试使用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);
}
答案 0 :(得分:1)
答案 1 :(得分:0)
要获得准确的答案,可能需要比您想象的更复杂的解析:考虑一下long
也可能被声明为long int
,并且long long
或{{ 1}}也是有效的变量声明。此外,您可以在同一行上声明多个变量,并且您不希望计算long long int
是较长单词的一部分的实例。
要快速了解一下,Linux工具int
和grep
可能会有所帮助:
wc
将列出文件的行数wc -l filename
将列出包含grep "for" filename | wc -l
的行数请注意,这些是近似值:如果for
在一行中出现多次,或者for
是for
之类的另一个单词的一部分,则仍然会计算一个实例。