Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Parsing a Text String

Status
Not open for further replies.

Kinl

Programmer
Mar 19, 2001
168
US
HI all,
I'm relatively new to the C programming language, and I'm trying to parse a text file, based on certain characters, such as a bracket < . Are there any functions out there, or how would I do this? I've looked in all my books and I cant seem to find anything. I'm figuring I'm going to have to loop through this and maybe put the data into an array, but I just dont know where to start. Also should I be using ctype.h or stdlib.h or both?!

Thanx for any help !

donn
 
Use fopen() to open the file and read it in text mode:

FILE *fp=fopen(a_file_name,&quot;r&quot;);

Use fgets() to read the file line by line. One way is to use an array of char if you have a good idea of the file data:

#define MAX_LINE 80

/* ... */

char line[MAX_LINE+1];

while (fgets(line,sizeof line,fp)) {
/* line will hold each line of the file */

/* ... */

If you're looking for a certain character in each line, you can use strchr() to find it:

if (strchr(line,'>')) {
/* '>' appears somewhere in line */

For these functions you'll just need <stdio.h> and <string.h>.

These functions and methods for doing what you're trying to accomplish should be covered in any good C book. Out of curiosity, which books do you have that you can't find info on this?

HTH,
Russ
bobbitts@hotmail.com
 
I have a C++ book that covers alot of the stuff, but I dont know whats backwards compatible. The C book I have covers C, C++, Java and some other languages, so the section on Strings is very short. It covers most of the functions that you used in your example, but it never went in depth on how to 'really use' them at all.

I appreciate the help, you've given me an edge on how to tackle this project when before I was kinda in the dark.
Thanx,

donn
 
For string parsing you can use strtok().

eg :
int main()
{
char str[] = &quot;Ths string to be parsed&quot;;
char *p;
printf(&quot;%s&quot;, strtok(str, &quot;<&quot;);
while( (p = strtok(NULL, &quot;<&quot;)) != NULL)
printf(&quot;%s&quot;, p);
return 0;
}

Note : This strtok() will alter the original string str. So If you wnat the original string to be unaltered then make a copy of the original string using strcpy() and pass the copy to the strtok().


Maniraja S
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top