将文件内容从特定位置获取到另一个特定位置
Get file content from specific position to another specific position
我想要通过指定位置的开始和位置的结束来获得文件内容的一部分。
我用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];
}
例如
以下是文件内容:
11619.
Mark Zeek.
39.
beside Marten st.
2/8/2013.
0
我只想得到以下部分:
39.
beside Marten st.
2/8/2013.
由于您知道要从文件中读取的块的开始和结束,因此可以使用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);
}
或者,如果你坚持使用裸指针并自己管理内存。。。
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
}
读取fstream的引用。在seekg
函数中,它们定义了一些您想要的ios_base
内容。我想你在找:
file.seekg(0,ios_base::end)
编辑:或者你想要这个?(直接取自电视参考,修改了一点,读取了我凭空提取的随机块)。
// 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;
}
首先可以使用
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;
}
但在您的情况下,为什么不使用getline()呢?
相关文章:
- 将值指定给向量(2D)的向量中的某个位置
- 使用Unreal C++获取VR耳机的世界位置/方向
- 写入位置0x0000000C时发生访问冲突
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 如何使用cudaMallocManaged在指针位置初始化对象?(C++)
- 无法获取webot::PositionSensor对象中位置传感器的值
- 非常量变量只读位置的赋值
- 如何定义更改car类中car位置的方法
- 使用迭代器时如何访问对象在向量中的位置?
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 求最大元素位置的分治算法
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 是与初始类同一内存位置的重新定位类
- 如何在使用网格布局时重叠qwidgets,并将重叠的widget定位在距离窗口边界特定距离的位置
- 我不知道如何定位最高随机数的位置
- 如何在MFC上设置窗口位置以将其定位到屏幕顶部
- 将QGraphicsSvgItem的中心定位在一个位置上。
- 如何定位WinRT异步方法调用中出现错误的位置
- 重定位表项在平面二进制文件中的存储位置