那么,我怎样才能读取整个文件
为了将整个文件读入内存缓冲区,您可以使用函数fread。通过附加一个终止空字符将输入转换为字符串后,您可以使用函数strstr 在输入中搜索某个单词。
这是一个执行此操作并在输入中搜索单词targetword的程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( void )
{
FILE *fp;
char buffer[1000];
size_t read;
//open input file
fp = fopen( "input.txt", "rt" );
if ( fp == NULL )
{
fprintf( stderr, "ERROR: Unable to open input file!\n" );
exit( EXIT_FAILURE );
}
//read entire file into buffer
read = fread( buffer, 1, sizeof buffer, fp );
//verify that buffer was not too small
if ( read == sizeof buffer )
{
fprintf( stderr, "ERROR: Memory buffer is too small to contain entire input!\n" );
exit( EXIT_FAILURE );
}
//add terminating null character to make input a valid
//null-terminated string
buffer[read] = '\0';
//search input for target word
if ( strstr( buffer, "targetword" ) != NULL )
printf( "Found word!\n" );
else
printf( "Did not find word!\n" );
fclose( fp );
}
然而,不是一次读取整个文件(这可能需要非常大的内存缓冲区),更常见的是在循环中一次读取一行,并且在每次循环迭代中,检查当前是否行包含您要查找的单词。这样,内存缓冲区只需足够大,即可一次存储一行输入,而不是整个输入。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int main( void )
{
FILE *fp;
char line[100];
bool found = false;
//open input file
fp = fopen( "input.txt", "rt" );
if ( fp == NULL )
{
fprintf( stderr, "ERROR: Unable to open input file!\n" );
exit( EXIT_FAILURE );
}
//read one line per loop iteration
while ( fgets( line, sizeof line, fp ) != NULL )
{
//verify that line was not too long to fit into buffer
if ( strchr( line, '\n' ) == NULL )
{
fprintf( stderr, "line too long to fit buffer!\n" );
exit( EXIT_FAILURE );
}
//search for target word
if ( strstr( line, "targetword" ) != NULL )
{
found = true;
break;
}
}
if ( found )
printf( "Found word!\n" );
else
printf( "Did not find word!\n" );
fclose( fp );
}
但是,这两种解决方案都有几个可能的问题:
-
如果目标词targetword 是另一个词的一部分,例如thetargetword,那么它会声明它找到了目标词。我不确定这是否是您想要的,或者您是否希望目标词单独出现。
-
如果目标词是syllabified,例如,target-\n 出现在一行中,word 出现在下一行,则程序将无法找到该词。
-
搜索是区分大小写的,所以它只会找到targetword,而不是Targetword 或TARGETWORD。
如有必要,所有这些问题都可以解决,但需要额外的工作。