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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

mid$, left$, right$ equivalance in C. 4

Status
Not open for further replies.

computerwhiz

Programmer
May 1, 2002
28
US
I am writing a program to parse certain information out of various length datafiles. I can read each line of the file as a record and write the same line to another file without any problems, but my problem is that I need to find a way to read the line of info and take out of that line only the information that is needed. example:

check 5053625
payee some vendor date 09/25/03

all I want is the check number from the first line, the vendor name and the actual date from the second line. I have no need for the other info. The datafile is much bigger but I think you got my point. I will be writing all of the data to a CSV file.
 
Hi,
If you work in C++, C# etc... you have the functions on your hand. In C you have to write some functions to parse a text. As I can see from your example, you could use strstr() to locate a occurence of a given string (if it is nedeed for example, "date" or "check" and strtok() to extract tokens from each line and process the tokens depending on their position ( 1st, 2nd, 3rd ...).
-obislavu-
 
In addition to the strtok method which works well if there is a known delimiter (or delimiters) between the information you want you can simulate the left$, right$ etc functions by using the strncpy() function.

Examples

/* Copy first 6 characters */
strncpy(dest, src, 6);
dest[6]=0x00;

/* Copy 5 characters from 3rd character */
strncpy(dest, src+2,5);
dest[5]=0x00;

/* Copy last 6 characters */
strncpy(dest,src+(strlen(src)-6),6);
dest[6]=0x00;

and so on.....
 
All the above solutions are correct. But in terms of simplicity, the easiest solution is given by SivaSwami.

I think he means sscanf() rather than sprintf().

All the formatting that you want to do will be taken care by the sscanf(). And that is what sscanf() there for.

And ofcourse newmangj is right, it will affect the performance also.

If you are to use your application for some real time system where performance can be an issue, avoid sscanf() and directly us pointers or use strtok() to break the string into tokens. Otherwise you can directly use sscanf()
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top