Extrat bytes from file

Hi,

I'm writing a simple program to extract the last X bytes/bits of a file.

So, to test my program I use 4 files:

image.jpg --> it is a image in jpg fomart. 13955 bytes.
sometext.txt --> is a text file with contain just 'sometext'. 9 bytes
both.file --> A file that contatin image.jpg + sometext.text. 13955 bytes + 9 bytes.
result --> Should be the same file as sometext.txt ( both.file - image.jpg )

I have created both.file my running 'cat image.jpg sometext.text > both.file'

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fstream file5 ("both.file", ios::in|ios::binary|ios::ate);
fstream file6 ("result", ios::out|ios::binary);

//Finding the file size.
size = file5.tellg();
file5.seekg (0,ios::beg); 

resultSize = 9;

file5.seekg (resultSize , ios::end);
memblock = new char [resultSize];

file5.read (memblock,resultSize);

file6.write(memblock,resultSize);

file5.close();
file6.close();

result is a file of 9 bytes. But it did not contain 'sometext'.
Just the lasts letters as you can see here

[joao@eddie cplusplus]$ od sometext.txt
0000000 067563 062555 062564 072170 000012
0000011

[joao@eddie cplusplus]$ od result
0000000 000000 000000 000000 000000 000012
0000011

So, can someone help to make my code work. I mean result be the same file as sometext.txt
The offset from ios::end should be negative. (line 10)
Last edited on
cire,

Thnak you so much! I did not do what u suggest. But your answer showed my mistake.

Here is the working code:

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
27
28

fstream file5 ("both.file", ios::in|ios::binary|ios::ate);
fstream file6 ("result", ios::out|ios::binary);

//Finding the file size.
size = file5.tellg();
file5.seekg (0,ios::beg); 

resultSize = 9;

file5.seekg (resultSize , ios::end);
memblock = new char [resultSize];

//The above line did the trick. It sets the position of the next character to be extracted from the input //stream.
//This postion is the first byte of sometext.txt. As I said, sometext is 9 bytes long. So I just need to read //9 bytes from this position.
//The trick is to set the postition to the first byte of the sometext.txt file. 
file5.seekg (13956,ios::beg); 


file5.read (memblock,resultSize);

file6.write(memblock,resultSize);

file5.close();
file6.close();


Topic archived. No new replies allowed.