0

Let's say i have a txt file:

Date: 11/11/11

Device: Boxster

Status: Good

I am trying to make my code search for a word (Say Device:), and display the info after that word (Boxster). So far i have the code working to only search for one word. How can i fix the code so that it can search 2 or 3 words, and display the info after them?

It would be even more helpful if i can display the info in the following format:

Boxster, 11/11/11, good.

Here is my code, thanks in advance!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {

    char file[100];
    char c[100];

    printf ("Enter file name and directory:");
    scanf ("%s",file);

    FILE * fs = fopen (file, "r") ;
    if ( fs == NULL )
    {
        puts ( "Cannot open source file" ) ;
        exit( 1 ) ;
    }

    FILE * ft = fopen ( "book5.txt", "w" ) ;
    if ( ft == NULL )
    {
        puts ( "Cannot open target file" ) ;
        exit( 1 ) ;
    }

    while(!feof(fs)) {
        char *Data;
        char *Device;
        char const * rc = fgets(c, 99, fs);

        if(rc==NULL) { break; }

        if((Data = strstr(rc, "Date:"))!= NULL)
            printf(Data+7);

        if((Data = strstr(rc, "Device:"))!=NULL)
            printf(Device+6);
    }

    fclose ( fs ) ;
    fclose ( ft ) ;

    return 0;

}
Dave Wang
  • 109
  • 4
  • 12
  • 1) feof() is wrong 2) `printf(Data+5);` should be `printf(Data+7);` 3) what is "dateL:" ? 4) strtok or strspn+strcspn might do the trick. – wildplasser Dec 27 '12 at 23:51

2 Answers2

0

Note some changes to printf and fgets You can use a logical or || to make multiple checks for a substring.

Try:

char rc[120]={0x0};
while(fgets(rc, sizeof(rc), fs)!=NULL) {
        char *Data;
        char *Device;

        if((Data = strstr(rc, "Date:"))!= NULL)
            printf("%s\n", &Data[7]);

        if((Device = strstr(rc, "Device:"))!=NULL ||
            (Device = strstr(rc, "String:"))!=NULL ||
            (Device = strstr(rc, "foo:"))!=NULL )
            printf("%s\n", &Device[6]);
    }

As you learn more about searching you may be able to implement regular expressions for searching, if your system supports that in C.

jim mcnamara
  • 16,005
  • 2
  • 34
  • 51
0

@DaveWang

Here is something i think that will work well for your requirements : https://www.dropbox.com/sh/108lz7k6z50kq7v/kmj6NYsuMT

Let me know if it helped

Nathan
  • 674
  • 8
  • 22