我试图让我的程序从另一个文件中读取字符串,为某些关键字解析它们,然后在它们出现在另一个文件中时将其添加到计数变量中。但是,除了行数之外,我似乎什么也没得到。我在这里怎么可能做错了?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// check that fp is not null omitted but needed
const char getLine[1] = "";
const char getFor[4] = "for";
char line[500];
int lineCount = 0;
int forCount = 0;
int x = 0;
int main() {
FILE* fp = fopen("file.txt", "r");
if (fp == NULL) {
perror("Error opening file");
return(-1);
}
while (fgets(line, 499, fp) != NULL) {
strstr(line, getLine);
lineCount++; //Essentially counting the number of lines in file.
}
printf("Line count is %d.\n", lineCount);
memset(line, 0, sizeof(line)); //Resetting the memory of line.
while (fgets(line, 499, fp) != NULL) {
char *findFor;
findFor = strstr(line, getFor);
if (findFor != NULL) { //Attempting to count each time an instant of 'for' appears.
forCount++;
}
}
printf("For count is %d.\n", forCount);
fclose(fp);
}
答案 0 :(得分:0)
代码正在读取整个文件以计数行数,但随后尝试再次读取它(没有rewind()
/ fseek()
)。因此,在第二个循环中,文件位于文件结尾。
没必要对行数进行计数,两个单独的循环中的“ for”仅需合计一次。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// check that fp is not null omitted but needed
const char getFor[4] = "for";
char line[500];
int lineCount = 0;
int forCount = 0;
int main( )
{
FILE *fp = fopen( "file.txt", "r" );
if ( fp == NULL )
{
perror( "Error opening file" );
return ( -1 );
}
while ( fgets( line, sizeof( line ), fp ) != NULL )
{
char *findFor;
findFor = strstr( line, getFor );
if ( findFor != NULL )
{
// Attempting to count each time an instance of 'for' appears.
forCount++;
}
lineCount++;
}
printf( "Line count is %d.\n", lineCount );
printf( "For count is %d.\n", forCount );
fclose( fp );
return 0;
}
此外,您还没有计算文件中“ for”的数量,而是计算其中包含“ for”的行的数量。如果一行有多个,则仅计为一个。