Stream.read operation in Tandem?

If I am using the ifstream.read method in c++ in an outer loop when reading the contents of a file and I then have an inner loop to ascertain a combination of values (in the example below, 5 bytes), then something strange happens. (strange to me anyway).

Lets say I am reading each character using the outer loop and I want to know when I reach the word wednesday. I first look for a 'w' and then use the inner loop (also a read method) to ascertain whether the next 5 characters are 'e','d','n','e','s' to check if I have found the word "wednesday".

If I do this the output up until I find the outer read while loop outputs a 'w' to the console.

The inner loop then outputs ednes

Then the outer loop goes on to output day.

I don't understand why the data read in the outer while loop skips over the values I am reading from an inner while loop. Is there a way of undoing what the inner loop does in order to output everything in the file through the outer loop? I hope this makes sense. Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int main()
{
   ifstream mystream;
   char *mychar = new char;
   char *target = new char;
   mystream.open("test.txt",ios::out | ios::binary);

while(mystream.read(mychar,1))
{

    cout << "///////////////////////" << mychar << endl;
    if (*mychar == 'w')
    {
       mystream.read(target,5);
       cout << target << endl;
    }

}
Last edited on
> mystream.open("test.txt",ios::out | ios::binary);

You've tried to open the file for output

> char *target = new char;

You don't have space to hold five chars

To use an array of char as a c-style string, it must be null-terminated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <fstream>

#define hello "hello"
#undef hello

int main()
{
    std::ifstream this_file( __FILE__ ) ; // open for input (std::ios::in)

    char my_char ;
    char directive[16] ;

    while( this_file.get(my_char) )
    {
        if( my_char == '#' ) //!!
        {
            std::cout << my_char ;

            this_file.read( directive, 7 ) ;
            directive[7] = 0 ; // null terminate

            std::cout << directive << '\n' ;
        }
    }
}

http://coliru.stacked-crooked.com/a/89c4411bc16fe9ed
Yes there are faults in my code. I've simply tried to give an ide of what I want to do.
I've since found the easy solution for this, which is designed to do exactly what I want to do. seekg
1
2
3
4
       streamoff off = -5;
       mystream.read(target,5);
       cout << *target << endl;
       mystream.seekg(off,ios_base::cur);
Topic archived. No new replies allowed.