I want a part of file content by specifying the beginning of position and specifying the end of position.
I'm using seekg
function to do that, but the function only determine the beginning position, but how determine the end position.
I'm did code to get the content of file from specific position to end of file, and save each line in item of array.
ifstream file("accounts/11619.txt");
if(file != NULL){
char *strChar[7];
int count=0;
file.seekg(22); // Here I have been determine the beginning position
strChar[0] = new char[20];
while(file.getline(strChar[count], 20)){
count++;
strChar[count] = new char[20];
}
For example
The following is the file content:
11619.
Mark Zeek.
39.
beside Marten st.
2/8/2013.
0
I want to get only the following part:
39.
beside Marten st.
2/8/2013.
Since you know the start and end of the block you want to read from the file you can use ifstream::read()
.
std::ifstream file("accounts/11619.txt");
if(file.is_open())
{
file.seekg(start);
std::string s;
s.resize(end - start);
file.read(&s[0], end - start);
}
Or if you insist on using naked pointers and managing the memory yourself...
std::ifstream file("accounts/11619.txt");
if(file.is_open())
{
file.seekg(start);
char *s = new char[end - start + 1];
file.read(s, end - start);
s[end - start] = 0;
// delete s somewhere
}
Read the reference for fstream. In the seekg
function, they define some ios_base
stuff you want. I think you're looking for:
file.seekg(0,ios_base::end)
Edit: Or perhaps you want this? (Taken straight from the tellg reference, modified a bit to read a random block that I pulled out of thin air).
// read a file into memory
#include <iostream> // std::cout
#include <fstream> // std::ifstream
int main () {
std::ifstream is ("test.txt", std::ifstream::binary);
if (is) {
is.seekg(-5,ios_base::end); //go to 5 before the end
int end = is.tellg(); //grab that index
is.seekg(22); //go to 22nd position
int begin = is.tellg(); //grab that index
// allocate memory:
char * buffer = new char [end-begin];
// read data as a block:
is.read (buffer,end-begin); //read everything from the 22nd position to 5 before the end
is.close();
// print content:
std::cout.write (buffer,length);
delete[] buffer;
}
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With