[英]How can I read different lines of a text file with fgets?
例如,如果 .txt 有
你好
那里。
寫在里面,無論fgets(str, N, file)
N 有多大,它都只會在 str 中存儲“Hello”,因為它會在找到 '\\n' 字符時停止。
那么,例如,如果我想在其中查找特定單詞,我如何讀取整個文件?
那么,我怎么能讀取整個文件
為了將整個流讀入內存緩沖區,您可以使用函數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
,那么它會聲明它找到了目標詞。 我不確定這是否是您想要的,或者您是否希望目標詞單獨出現。
如果目標詞是音節化的,例如, target-\\n
出現在一行中,而word
出現在下一行,那么程序也將無法找到該詞。
如果需要,這兩個問題都可以解決,但需要額外的工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.