How to find a particular string occurance position in a file?
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
How to find a particular string occurance position in a file?
I have a program which will write informations like gid,gname,resname,restype,etc... in a file.I wrote a function to get the starting and ending position of a particular group.Stating of a particular group (say group 12)is denoted in a file by #gid12 and the end of the group is denoted by @gid12.I don't know wat mistake i have done. The code works correctly only for the 1st group in the file. when i try to get other groups information i am getting wrong output.Plz tel me wat is the bug in my program.And is there any other way to find the starting and ending position of a particular group from my file.
Also, as Sergei said, unless this is homework for a class on C, I cannot image why you would want to do this in C. A language like Perl, Python or Ruby would be much easier.
strstr will return the first instance of the substring in a string. So you read the whole file into a buffer, then search for the first instance of your substring using strstr. After you find the first instance, you set a pointer to point to the end of that substring, then repeat strstr using that pointer as the beginning of the string you are searching. Strstr will then return the next instance of the substring.
Just repeat this in a loop until you have found all instances. The pointer values returned by strstr are the distance into the file you have gone to find the information you are looking for.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.