我的问题是,我试图只读取给定 n 个文件的一定数量的文件。
例如,我有两个文件,其中包含以下内容
test1:
A cat ran off
Apple
test2:
The boy went home
Apples are red
我想要的输出是
test1: A cat ran off
不是
test1: A cat ran off
test2: Apples are red
这是我到目前为止编写的代码:
#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);
}
最佳答案
继续评论,并注意到您需要删除结尾的 newline
包含于fgets
,您可以执行如下操作:
#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--
进行迭代您的文件会被反向处理,因此您最终会得到如下输出:
$ ./bin/searcher test2 test1
test1: A cat ran off
$ ./bin/searcher test1 test2
test2: Apples are red
注意:要按顺序处理文件,只需执行类似 for (i = 1; i < argc; i++)
的操作即可而不是while (argc--)
。如果您还有其他问题,请告诉我。
更改为for
循环而不是 while
在main
并输入10
作为要查找的出现次数,所有 文件都会被处理,例如:
$ ./bin/searcher test1 test2
test1: A cat ran off
test2: Apples are red
关于c - 如何用C从文件中读取特定数量的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38035795/