View Full Version : File Input/Output Help
frog.frog
07-21-2006, 02:11 AM
Hi. I am writing a program in C++ which requires the "analyzation" and output of text files.
What I'm looking to accomplish is have it search a text file until it finds a particular word, and then print all following lines until it reaches the next 'particular word' and stops output.
If that is not clear enough, an example: The program loads the following text and begins output at START and stops output at STOP.
a bunch of text a bunch of text
a bunch of text a bunch of text
a bunch of text a bunch of text
START
bla bla bla bla
bla bla bla bla
bla bla bla bla
STOP
a bunch of text a bunch of text
I can't find any information on how I would go about doing this, though. Any help would be appreciated.
daniel_g
07-21-2006, 05:25 AM
Would you be able to solve the problem if it was to get direct user imput of either a string or a number instead of scanning a txt document?
If yes, I recommend you start by doing exactly that. When that program works to perfection, then you can easily modify it to scan a text document instead of waiting for user imput. That's the easiest way to start.
If no, where exactly are you getting stuck?
frog.frog
07-21-2006, 06:08 AM
I know very little about file i/o. I've been searching around for articles detailing beyond printing to and from text files, but I can't find any.
What I'm looking for is how to do it at all, actually =P.
That is, without readingfrom 20,000 different text files--I could do that no problem. I want to be able to "compress" it into one text file and maintain the same functionality.
paulq
07-21-2006, 06:46 PM
Are you printing to device (printer) or printing to stdout (screen)?
frog.frog
07-21-2006, 08:46 PM
stdout.
paulq
07-21-2006, 09:31 PM
http://www.cplusplus.com/ref/iostream/fstream/: Here are the functions you would use. All you would need to do is the following (psuedo code):
f fstream;
f.open(file_name);
if(f.is_open())
{
char * magic_word = 'word';
int len = strlen(magic_word);
int test = 0;
while(!f.eof())
{
read(buffer, bufferLength);
for(int x = 0; x < bufferLength; x++)
{
if(buffer[x] == magic_word[x])
test++;
else
test = 0;
if(test == len)
{
printf("word found");
break;
}
}
}
}
I have no idea if that's what you want or need or even if it's a decent way of doing it. It's just the first thing to come to mine....and I am tired. If you have the magic_word on its own line, things could be easier using cin.getline or something. Good luck.
frog.frog
07-21-2006, 11:20 PM
Thank you very much! Though your code wasn't what I was looking for, it did show me the one thing I had completely overlooked: if (magic_word=="word").
Thinking about it now, I had made the assumption that I couldn't possibly know how to do it and not bothered to consider the obvious. Thanks for the slap in the face =P.
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.