Thread: Get all lines with the word time in it.

  1. #1
    Registered User
    Join Date
    Jun 2019
    Posts
    44

    Get all lines with the word time in it.

    File.txt
    Jerry Owen
    Start time was 1:45PM
    bla bla bla
    bla bla bla
    bla bla bla
    Byron Owen
    Start time was 2:45PM
    bla bla bla
    bla bla bla
    bla bla bla
    bla bla bla
    bla bla bla
    Kathy Owen
    Start time was 3:45PM

    bla bla bla

    ……………


    I’m trying to get all lines with the word time in it. How do I make this work? The only thing it does right now is to find the word “time”, but only one, and fgets does nothing with the line for me.

    grep works well:
    grep time file.txt
    but I need to do everything in C.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    #define MAX 15
    #define FIND "time"
    
    char fileText[14];
    
    int main() {
    
    FILE *fptr, *fptw;
      fptr=fopen("file.txt","r");
    
      fseek(fptr, 0, SEEK_END);
      long pos = ftell(fptr); 
      fseek(fptr, 0, SEEK_SET);
    
      char *arr = malloc(pos + 1);
      fread(arr, pos, 1, fptr);
      arr[pos] = '\0'; 
    
    
        if (strstr(arr, FIND) != 0){
            fgets(fileText, MAX, fptr); 
    
            printf("found\n");
            printf("%s\n\n",fileText); }
       else{
           printf("Not found\n"); }
    
       free(arr);
    
      return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Like so.
    Code:
    char buff[BUFSIZ];
    while ( fgets(buff,BUFSIZ,fptr) != NULL ) {
        if ( strstr(buff,FIND) != NULL ) {
            printf("Found %s", buff);
        }
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 03-22-2014, 10:46 PM
  2. Replies: 10
    Last Post: 04-10-2011, 06:52 AM
  3. Word Sort--Again, but this time in C++
    By abh!shek in forum C++ Programming
    Replies: 5
    Last Post: 02-04-2008, 12:19 PM
  4. Printing 20 lines at a time
    By csmatheng in forum C Programming
    Replies: 5
    Last Post: 04-30-2002, 04:11 PM
  5. Replies: 3
    Last Post: 02-08-2002, 10:15 PM

Tags for this Thread