[英]How to read a specific amount of lines from a file in C
我的問題是,給定n個文件,我試圖僅讀取一定數量的文件。
例如,我里面有兩個文件,其內容如下
測試1:
一只貓跑了
蘋果
測試2:
這個男孩回家了
蘋果是紅色的
我希望輸出是
test1:一只貓跑了
不
test1:一只貓跑了
test2:蘋果是紅色的
這是我到目前為止編寫的代碼:
#include <stdio.h>
#include <string.h>
int main (int argc, char ** argv)
{
extern int searcher(char * name, char*search,int amount);
while(argc != 0){
if(argv[argc] !=NULL)
if(searcher(argv[argc],"a",1)) break;
argc-- ;
}
}
int searcher(char * name, char*search,int amount){
FILE *file = fopen (name, "r" );
int count = 0;
if (file != NULL) {
char line [1000];
while(fgets(line,sizeof line,file)!= NULL && count != amount)
{
if(strstr(line,search) !=NULL){
count++;
if(count == amount){
return(count);
}
printf("%s:%s\n", line,name);
}
}
fclose(file);
}else {
perror(name); //print the error message on stderr.
}
return(0);
}
從注釋繼續,並注意到您將需要刪除fgets
包含的結尾newline
,您可以執行以下操作:
#include <stdio.h>
#include <string.h>
enum { MAXC = 1000 };
int searcher (char *name, char *search, int amount);
void rmlf (char *s);
int main (int argc, char **argv)
{
int i;
for (i = 1; i < argc; i++)
if (searcher (argv[i], "a", 1))
break;
return 0;
}
int searcher (char *name, char *search, int amount)
{
FILE *file = fopen (name, "r");
int count = 0;
if (!file) {
fprintf (stderr, "error: file open failed '%s'.\n", name);
return 0;
}
char line[MAXC] = "";
while (count < amount && fgets (line, MAXC, file)) {
rmlf (line); /* strip trailing \n from line */
if (strstr (line, search)) {
count++;
printf ("%s: %s\n", name, line);
}
}
fclose (file);
return count == amount ? count : 0;
}
/** stip trailing newlines and carraige returns by overwriting with
* null-terminating char. str is modified in place.
*/
void rmlf (char *s)
{
if (!s || !*s) return;
for (; *s && *s != '\n'; s++) {}
*s = 0;
}
輸入文件示例
$ cat test1
A cat ran off
Apple
$ cat test2
The boy went home
Apples are red
使用/輸出示例
您了解使用argc--
迭代argc--
您的文件將以相反的方式處理,因此最終將得到如下輸出:
$ ./bin/searcher test2 test1
test1: A cat ran off
$ ./bin/searcher test1 test2
test2: Apples are red
注意: while (argc--)
順序處理文件,只需執行for (i = 1; i < argc; i++)
而不是while (argc--)
。 如果您還有其他問題,請告訴我。
更改為for
循環而不是main
中的while
並輸入10
作為要查找的出現次數,將處理所有文件,例如:
$ ./bin/searcher test1 test2
test1: A cat ran off
test2: Apples are red
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.