C++ 从特定位置获取文件内容到另一个特定位置

C++ 从特定位置获取文件内容到另一个特定位置,c++,file,C++,File,我希望通过指定位置的开始和结束来指定文件内容的一部分 我使用的是seekg函数,但该函数只确定起始位置,但如何确定结束位置 我使用did代码从文件的特定位置到文件的末尾获取文件内容,并将每一行保存在数组项中 ifstream file("accounts/11619.txt"); if(file != NULL){ char *strChar[7]; int count=0; file.seekg(22); // Here I have been determine the b

我希望通过指定位置的开始和结束来指定文件内容的一部分

我使用的是
seekg
函数,但该函数只确定起始位置,但如何确定结束位置

我使用did代码从文件的特定位置到文件的末尾获取文件内容,并将每一行保存在数组项中

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];
}
例如
以下是文件内容:

11619.
Mark Zeek.
39.
beside Marten st.
2/8/2013.
0
我只想得到以下部分:

39.
beside Marten st.
2/8/2013.
请阅读参考资料。在
seekg
函数中,它们定义了一些您想要的
ios\u base
内容。我想你在寻找:

file.seekg(0,ios_base::end)
编辑:或者你想要这个?(直接取自参考资料,修改了一点以读取我凭空提取的随机块)

//将文件读入内存
#include//std::cout
#include//std::ifstream
int main(){
std::ifstream是(“test.txt”,std::ifstream::binary);
如果(是){
is.seekg(-5,ios_base::end);//在结束之前转到5
int end=is.tellg();//获取该索引
is.seekg(22);//转到第22位
int begin=is.tellg();//获取该索引
//分配内存:
char*buffer=新字符[结束-开始];
//将数据作为块读取:
is.read(缓冲区,结束开始);//读取从第22位到结束前5位的所有内容
is.close();
//打印内容:
std::cout.write(缓冲区、长度);
删除[]缓冲区;
}
返回0;
}

由于您知道要从文件中读取的块的开始和结束,因此可以使用
ifstream::read()

或者如果你坚持使用裸指针并自己管理内存

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
}
首先,你可以使用

seekg()
要设置读取位置,则可以使用

read(buffer,length)
阅读意图

例如,您希望读取名为test.txt的文本文件中从第6个字符开始的10个字符,以下是一个示例

#include<iostream>
#include<fstream>

using namespace std;

int main()
{
std::ifstream is ("test.txt", std::ifstream::binary);
if(is)
{
is.seekg(0, is.end);
int length = is.tellg();
is.seekg(5, is.beg);

char * buffer = new char [length];

is.read(buffer, 10);

is.close();

cout << buffer << endl;

delete [] buffer;
}
return 0;
}
#包括
#包括
使用名称空间std;
int main()
{
std::ifstream是(“test.txt”,std::ifstream::binary);
如果(是)
{
is.seekg(0,is.end);
int length=is.tellg();
is.seekg(5,is.beg);
字符*缓冲区=新字符[长度];
读(缓冲器,10);
is.close();

噢,请使用
std::string
std::getline
@Nawaz:但是我想使用c样式的字符串。如果你知道开始位置和结束位置,你不能只计算要读取的字符数,并将其作为第二个参数传递给我吗?谢谢,但我知道
ios_base::end
,我不想读取到文件结尾。我想要从特定文件偏移量到特定文件偏移量的文件内容的一部分……你的意思是?我确信引用会告诉你你想要知道的……谢谢,但我想使用c样式字符串。@LionKing你不能使用s.c_str(),或使用char*而不是string;@LionKing不知道你为什么坚持使用裸指针,但我已经更新了我的示例。@Captain Obvlious:请告诉我
s[end-start]=0;
?@LionKing它在字符串末尾添加了一个空终止符。
read(buffer,length)
#include<iostream>
#include<fstream>

using namespace std;

int main()
{
std::ifstream is ("test.txt", std::ifstream::binary);
if(is)
{
is.seekg(0, is.end);
int length = is.tellg();
is.seekg(5, is.beg);

char * buffer = new char [length];

is.read(buffer, 10);

is.close();

cout << buffer << endl;

delete [] buffer;
}
return 0;
}