![]() |
Hello and Welcome from United States to the UNIX and Linux Forums! Thank You for Visiting and Joining Our Global Community.
|
|
google unix.com
|
|||||||
| Forums | Register | Forum Rules | Links | Albums | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
| High Level Programming Post questions about C, C++, Java, SQL, and other programming languages here. |
More UNIX and Linux Forum Topics You Might Find Helpful
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| how can search a String in one text file and replace the whole line in another file | kkraja | UNIX for Dummies Questions & Answers | 6 | 08-06-2008 07:23 AM |
| Search a string and append text after the string | kesu2k | Shell Programming and Scripting | 8 | 07-18-2008 07:35 PM |
| search text string | itik | AIX | 2 | 01-28-2008 07:01 PM |
| Perl: Search for string on line then search and replace text | Crypto | Shell Programming and Scripting | 4 | 01-04-2008 10:24 AM |
| appending string to text file based on search string | malaymaru | Shell Programming and Scripting | 1 | 06-09-2006 08:53 AM |
![]() |
|
|
LinkBack | Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
||||
|
Search a string in a text file in C
Hello,
I need help with a program i'm coding in C. What my program has to do is to search a string in a text file, if it finds a match, print the string to stdout. The file looks like: 000001 California 100000 Texas 011110 Ohio 010101 Washington So, if the program finds a match, prints "100000 Texas" to stdout. Could you help me? Please excuse my poor english. |
|
||||
|
Code:
/* srch.c usage: srch filename "string to find"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
FILE *fp=fopen(argv[1],"r");
char tmp[256]={0x0};
while(fp!=NULL && fget(tmp, sizeof(tmp), fp)!=NULL)
{
if (strstr(tmp, argv[2])
printf("%s", tmp);
}
if(fp!=NULL) fclose(fp);
return 0;
}
|
|
||||
|
Thank You!!!, Thanks man,... Thank you...
I corrected 'fgets' and 'if' functions... Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
FILE *fp=fopen(argv[1],"r");
char tmp[256]={0x0};
while(fp!=NULL && fgets(tmp, sizeof(tmp),fp)!=NULL)
{
if (strstr(tmp, argv[2]))
printf("%s", tmp);
}
if(fp!=NULL) fclose(fp);
return 0;
}
|
|
||||
|
No the search is line-by-line, fgets gets one line at a time. tmp[256] can read in as many as 255 chars. No line in the example text is longer than 40. No issue.
As a general solution, use tmp[LINE_MAX] where LINE_MAX is defined in limits.h Most UNIX tools limit line size to whatever LINE_MAX is for your system. |
![]() |
| Bookmarks |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|