StreamReader

Dear sir

i have a problem with seek in StreamReader, my problem is

i want to read the contain of a text file, but the reading is done like this ( read first row, then 5th row, then 10th row, ... to nth row of data inside the file and finaly return the number of reading (n\5)). the code i am using is shown below. but the problem is the StreamReader pointer is not jumping 5 positions , it just read the next position even if i used "BaseStream->Seek".

FileStream fs = File::OpenRead("samples.txt");
StreamReader sw = gcnew StreamReader(fs);
samplestep = 0;
while (sw->ReadLine())
{
sw->BaseStream->Seek(5,System::IO::SeekOrigin::Current);
samplestep++;
}
sw->Close();
fs->Close();


the file sample contains

1
389
-6
1
0
1
388
8
1
0
1
387
11
1
0
1
386
13
1
0
1
385
16
1
0
384
384
18
1
0
1
383
21
1
0
1
382
23
1
0
1
381
26
1
0
1
281
-27
1
0
1
282
-25
1
0
1
283
-22
1
0
1
284
-20
1
0
1
285
-17
1
0
1
286
-15
1
0
1
287
-12
1
0
1
288
-10
1
0

so is there another way to read the contain of a file every 5 rows, by the way

i tried a different way by reading all the file and divide by 5 but this approach is time consuming since the file is about 119236 values ( the code below)

FileStream ^fs = File::OpenRead("samples.txt");
String ^line;
StreamReader ^sw = gcnew StreamReader(fs);
samplestep = 0;
while (line = sw->ReadLine())
{
samplestep++;
}
sw->Close();
fs->Close();
samplestep = samplestep / 5;


with best wishes

As I think "seek'" changes current position in file. Position is a ony byte, it's not one string
you need use something like
1
2
3
4
5
6
7
8
9
10
FileStream fs = File::OpenRead("samples.txt");
StreamReader sw = gcnew StreamReader(fs);
int count = 0;
while (sw->ReadLine())
{
    ++count;
}
count /= 5;
sw->Close();
fs->Close();
Last edited on
thank you Denis for your reply
i mentioned using the code you wrote , but for a big file it will take a long time , is there a way to read every 5 row not read all the file and divide by 5. If it is not seek is there any other function that change the pointer of the streamReader

with best wishes
closed account (S6k9GNh0)
As hard as I've tried to come with a way, I can't currently think of one... I seem to be stooped though I believe it's possible.
In general, unless you are reading 1% or less of a file, it is faster to just read the entire file. Seeks will slow you down.

The fastest way to do what you want is to mmap the file and then just count the number of record delimiters, stopping to process the data you want.

Any reason you think this belongs in General C++ rather than the Windows Programming forum?
Dear PanGalactic

thank you for your reply, i did what you suggest and it reduce the time to 2/3 of the original time ,


i posted it in General c++ rather than Windows programming because i do not think this related to windows programming and it is more general.
Topic archived. No new replies allowed.