我想通过指定位置的开头并指定位置的结尾来获取文件内容的一部分。
我使用seekg函数来做到这一点,但是函数仅确定开始位置,但是如何确定结束位置。
我做了代码以从特定位置到文件末尾获取文件内容,并将每一行保存在数组项中。
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];
}
Run Code Online (Sandbox Code Playgroud)
例如
,以下是文件内容:
11619.
Mark Zeek.
39.
beside Marten st.
2/8/2013.
0
Run Code Online (Sandbox Code Playgroud)
我只想得到以下部分:
39.
beside Marten st.
2/8/2013.
Run Code Online (Sandbox Code Playgroud)
由于您知道要从文件中读取的块的开始和结尾,因此可以使用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);
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您坚持使用裸指针并自己管理内存...
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
}
Run Code Online (Sandbox Code Playgroud)