【问题标题】:Printing a line read from a file containing a particular word打印从包含特定单词的文件中读取的行
【发布时间】:2015-07-20 20:43:21
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()

{
  int i, p=0;;
    int c;
    char file_name[100];
    char  search[10];

    printf("Enter the file name:");
    scanf("%s", file_name);
    printf("Search word:");
    scanf("%s", search);

    FILE *f = fopen((strcat(file_name, ".txt")), "rb");
    fseek(f, 0, SEEK_END);
    long pos = ftell(f); 
    fseek(f, 0, SEEK_SET);

    char *bytes = malloc(pos + 1);
    fread(bytes, pos, 1, f);
    bytes[ pos ] = '\0'; 

/*search*/

    if (strstr(bytes, search) != NULL){
        printf("found\n");
        p = 1;}
    else{
        printf("Not found\n");

        p=0;}

    free(bytes);

   char *found = strstr( bytes, search );
   if ( found != NULL )
   {
    char *lineStart;
    for(lineStart = strchr(bytes, '\n');  !strcmp(lineStart,"\n"); 
        lineStart = strchr(lineStart+1, '\n')){
      printf("%s\n", lineStart);  
   }
  }
}

上述代码应该在文件(.txt) 中搜索一个单词,如果找到它应该打印"found" 并打印找到它的行。例如,如果在文件中搜索一个单词"Brick"文件,如果在类似"The house is made of red bricks" 的句子中找到,则将整个句子打印为输出,即"The house is made of the red bricks"

我无法打印包含搜索词的行。我正在尝试使用指针移动到当前行的开头,然后增量导航,但我有点卡在如何使指针停在行尾并一直打印到该点。

【问题讨论】:

  • free 移动到您不再需要它的位置,例如。最后
  • @Hi-Angel 好吧,你可以。 :-) c99 以后。
  • @Hi-Angel 恕我直言,您可以删除评论。不知何故,这是一种误导。希望你能理解。 :-)

标签: c pointers file-io printf free


【解决方案1】:

您的代码的问题是,您在代码中调用free(bytes);,然后继续使用bytes。这会调用undefined behavior

另外,我会建议

  1. 更改您的 scanf() 指令

    scanf("%s", file_name);
    

    scanf("%s", search);
    

    scanf("99%s", file_name);
    

    scanf("9%s", search);
    

    避免缓冲区溢出的风险。

  2. 在使用返回的指针之前,始终检查fopen() 是否成功。

不过,从逻辑上来说,我会建议你

  1. 使用fgets()从文件中逐行读取整个
  2. 使用strstr() 搜索特定单词。
  3. 如果找到,则打印整行,否则,继续执行步骤 1,直到 fgets() 返回 NULL。

注意事项:

  1. main() 的推荐签名是int main(void)
  2. 始终初始化所有局部变量。

【讨论】:

  • in 3. 如何打印整行?
  • @diplodocus 好吧,fgets() 中提供的输入缓冲区将包含整行。但是,您可能需要自己处理 trailinh newline
  • 但是如果这个词在句子的中间呢?在那种情况下 fgets() 不会继续到行尾,不是吗?
  • @diplodocus 嗯,fgets() 读取整行,直到\nEOF。请查看我提供的链接中的手册页。
猜你喜欢
  • 2014-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
相关资源
最近更新 更多