【问题标题】:Search_string in a loop of different files in CSearch_string 在 C 中不同文件的循环中
【发布时间】:2017-02-09 14:42:25
【问题描述】:

我不知道如何解决这个问题。我有这个功能可以打印我拥有的所有 .txt 文件,但我还需要在每个文件名之后搜索并打印一些包含某些单词的特定字符串(每个文件的)。 这是打印文件名的部分。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <dirent.h>

int main() {

    DIR* p;
    struct dirent* pp;
    p = opendir("./");

    if (p != NULL) {

        while ((pp = readdir(p)) != NULL) {
            int length = strlen(pp->d_name);
            if (strncmp(pp->d_name + length - 4, ".txt", 4) == 0)
                puts(pp->d_name);
        }

        (void)closedir(p);
    }

    return 0;
}

我需要搜索一些特定的词(三个不同的词)并打印其中包含的行,这将是三个不同的行。

现在程序打印这个:

0_email.txt
1_email.txt

在这个类似于电子邮件的文件中,我需要打印发送日期(日期:)、谁(收件人:)和主题(主题:)。这些信息并不总是在同一行。 我试过这个代码,搜索这个词,但我不能让程序在所有文件中搜索(因为这个文件可以增加并且有不同的名字,不,我不能不按名字来做)和多次搜索

FILE *fp;

    char filename[]="0_email.txt",line[200],search_string[]="To:";

    fp=fopen(filename,"r");

    if(!fp){
            perror("could not find the file");
            exit(0);
   }
    while ( fgets ( line, 200, fp ) != NULL ){

            if(strstr(line,search_string))
            fputs ( line, stdout );
    }

    fclose ( fp );

第二段代码是我在网上找的,刚学c编程,不太熟悉。

感谢您的帮助!

【问题讨论】:

  • 你能不能更具体一些,给我们看一个例子?
  • 那么对于.txt 文件,您需要打开它们并读取文件的一部分并打印出来吗?那你为什么不尝试一下而不是只打印文件名呢?
  • 我已经上传了更多信息。
  • 我必须打印他的文件名和其中的一些行
  • 如果你正在学习 C,首先要学习如何正确缩进你的代码。这是非常非常重要的。

标签: c file search netbeans printf


【解决方案1】:

你需要了解函数。

你大致需要以下内容:

这是未经测试的代码,还有很多需要改进的地方。它不完全你想要什么,我什至不确定它是否编译,但它应该让你知道你需要做什么:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <dirent.h>

int CheckFile(const char *filename)
{
  FILE *fp;

  char line[200], search_string[] = "To:";

  fp = fopen(filename, "r");

  if (!fp) {
    perror("could not find the file");
    exit(0);
  }

  while (fgets(line, 200, fp) != NULL) {
    if (strstr(line, search_string))
      fputs(line, stdout);
  }

  fclose(fp);
}


int main() {    
    DIR* p;
    struct dirent* pp;
    p = opendir("./");

    if (p != NULL) {

        while ((pp = readdir(p)) != NULL) {
            int length = strlen(pp->d_name);
            if (strncmp(pp->d_name + length - 4, ".txt", 4) == 0)
              CheckFile(pp->d_name);
        }

        (void)closedir(p);
    }

    return 0;
}

【讨论】:

  • 我知道我必须改进很多事情,但现在我知道该做什么了。感谢您的帮助!
猜你喜欢
  • 2021-05-06
  • 1970-01-01
  • 1970-01-01
  • 2019-09-03
  • 2013-11-20
  • 1970-01-01
  • 1970-01-01
  • 2014-02-19
  • 1970-01-01
相关资源
最近更新 更多