c - 如何用C从文件中读取特定数量的行

标签 c file output

我的问题是,我试图只读取给定 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循环而不是 whilemain并输入10作为要查找的出现次数,所有 文件都会被处理,例如:

$ ./bin/searcher test1 test2
test1: A cat ran off
test2: Apples are red

关于c - 如何用C从文件中读取特定数量的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38035795/

相关文章:

c - 如何跟踪泄漏了多少内存?

android - 为什么 "tcsetattr(fd, TCSANOW, &cfg)"总是失败?

python - 为什么逐行复制文件会极大地影响 Python 中的复制速度?

python - 如何在ram中创建目录并获取路径?

c - 为什么 sprintf 在一个例子中起作用,而在下一个例子中不起作用?

c - 如何调试Linux内核的特定代码?

C const - 如果 const 是右值(即未存储在内存中),指向 const 的指针如何可能?

java - 如果重新实例化它,我是否应该多次关闭 FileInputStream

c++ - 在不确定的时间内按住某个键

Luigi Python 中的 MongoDB