Re: [C] how to search a string ?
From: Richard Heathfield (dontmail_at_address.co.uk.invalid)
Date: 10/23/03
- Next message: Mac: "Re: [C] how to search a string ?"
- Previous message: Mac: "Re: calculating 64 bit hexadecimals"
- In reply to: Alan: "[C] how to search a string ?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Thu, 23 Oct 2003 04:24:18 +0000 (UTC)
[Followups set to acllcc++]
Alan wrote:
> I want to search a string in a file, but I don't know the position, how
> can I search the string and stop at that line containing that string ?
>
> for example, I want to seach the string ".ABC" in a file, how to do ?
Read the string one line at a time. If you know the longest line you can
expect, then fgets is suitable for this. If you don't, consider using
something along the same lines as my fgetline function, which you can get
from:
http://users.powernet.co.uk/eton/c/fgetline.h
http://users.powernet.co.uk/eton/c/fgetline.c
Using my code, the problem is easily solved:
#include <stdio.h>
#include <string.h>
#include "fgetline.h"
int main(int argc, char **argv)
{
if(argc > 2)
{
FILE *fp = fopen(argv[1], "r");
if(fp != NULL)
{
char *line = NULL;
size_t size = 0;
while(0 == fgetline(&line, &size, (size_t)-1, fp, 0))
{
if(strstr(line, argv[2]) != NULL)
{
printf("%s\n", line);
}
}
free(line);
fclose(fp);
}
else
{
handle the file-opening error correctly
}
}
else
{
explain to the user how to use the program
}
return 0;
}
If you'd rather use fgets:
#include <stdio.h>
#include <string.h>
#define MAXLINE 1024 /* change this if necessary */
int main(int argc, char **argv)
{
if(argc > 2)
{
FILE *fp = fopen(argv[1], "r");
if(fp != NULL)
{
char line[MAXLINE + 2] = {0};
while(fgets(line, sizeof line, fp) != NULL)
{
if(strstr(line, argv[2]) != NULL)
{
printf("%s", line);
}
}
fclose(fp);
}
else
{
handle the file-opening error correctly
}
}
else
{
explain to the user how to use the program
}
return 0;
}
-- Richard Heathfield : binary@eton.powernet.co.uk "Usenet is a strange place." - Dennis M Ritchie, 29 July 1999. C FAQ: http://www.eskimo.com/~scs/C-faq/top.html K&R answers, C books, etc: http://users.powernet.co.uk/eton
- Next message: Mac: "Re: [C] how to search a string ?"
- Previous message: Mac: "Re: calculating 64 bit hexadecimals"
- In reply to: Alan: "[C] how to search a string ?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|