![]() |
Search for text in a file
Is there any way to search for text in a file (not part of the program) and then read the following text until it sees a certain line of text. For example:
Hello World. How are you today? I am fine. is the text file, and I want the program to search for 'World.' then read the text (and use it, say as an output) and stop when it sees 'I am', without knowing what is between. Thank you. |
Re: Search for text in a file
There's two options. You can use the C++ standard library and read in a file with ifstream, or use a FILE* pointer and fopen() and read in the file the old-fashioned way with cstdio. If you need an explanation on how to open and read a file, feel free to post here again or PM me. Once you've opened the file, you have to options.
1. You can read the entire text file all at once into a memory buffer and then search for your text using strstr(), which returns a pointer to the start of the sub-string you searched for. 1. Alternatively, you can read in the file line at a time (using gets() with FILE* pointers/fopen() and ifstream::getline() for ifstream) and search each line you load in with strstr(). If you're using FILE* pointers, don't forget to call fclose() on the file when you're done. As I said, feel free to let me know if you need any more help. |
Re: Search for text in a file
Can you show me an example program please?
|
Re: Search for text in a file
Gladly. Before I do, one question though:
Quote:
|
Re: Search for text in a file
Karatekid: it almost sounds like you're just looking for a generic tool to search for text, as opposed to something as part of your code. If thats the case, then I'd recommend grep. For windows, you can get it at http://gnuwin32.sourceforge.net/packages/grep.htm
Grep is pretty easy to use for basic things. Go to a command line and type Code:
grep "text to search for" filename |
Re: Search for text in a file
I want it to find 'World' then output the text until it finds 'I am'
|
Re: Search for text in a file
Got it. You'll have a demo program later today.
|
Re: Search for text in a file
Ok. Thank you very much.
|
Re: Search for text in a file
Share and enjoy.
PHP Code:
|
Re: Search for text in a file
From the checking I did, this will work. However, it also seems to be the way to do it in C and not the primary way to do such in c++. If anyone knows the c++ formatting to do this, it would be helpful.
|
Re: Search for text in a file
As I said, this is the "C way" to do it, but all the C libraries work perfectly well in C++. This won't put you at a disadvantage in any way. If you want to do it the "C++ way," just read your data into the buffer with ifstream. That's all you have to change.
|
| All times are GMT -5. The time now is 12:20. |
Powered by vBulletin® Version 3.6.4
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
Copyright © Chief Delphi