我需要将整个文件读入内存并将其放在C++中std::string.
如果我把它读成a char[],答案很简单:
std::ifstream t;
int length;
t.open("file.txt"); // open input file
t.seekg(0, std::ios::end); // go to the end
length = t.tellg(); // report location (this is the length)
t.seekg(0, std::ios::beg); // go back to the beginning
buffer = new char[length]; // allocate memory for a buffer of appropriate dimension
t.read(buffer, length); // read the whole file into the buffer
t.close(); // close file handle
// ... Do stuff with buffer here ...
Run Code Online (Sandbox Code Playgroud)
现在,我想做同样的事情,但是使用a std::string而不是a char[] …
让我们为这个问题创建一个补充问题.在C++中获取文件大小的最常用方法是什么?在回答之前,确保它是可移植的(可以在Unix,Mac和Windows上执行),可靠,易于理解且没有库依赖(没有boost或qt,但是例如glib是可以的,因为它是可移植的库).
我做了一个示例项目,将文件读入缓冲区.当我使用tellg()函数时,它给我一个比读取函数实际读取的值更大的值.我认为有一个错误.
这是我的代码:
编辑:
void read_file (const char* name, int *size , char*& buffer)
{
ifstream file;
file.open(name,ios::in|ios::binary);
*size = 0;
if (file.is_open())
{
// get length of file
file.seekg(0,std::ios_base::end);
int length = *size = file.tellg();
file.seekg(0,std::ios_base::beg);
// allocate buffer in size of file
buffer = new char[length];
// read
file.read(buffer,length);
cout << file.gcount() << endl;
}
file.close();
}
Run Code Online (Sandbox Code Playgroud)
主要:
void main()
{
int size = 0;
char* buffer = NULL;
read_file("File.txt",&size,buffer);
for (int i = 0; i < size; i++) …Run Code Online (Sandbox Code Playgroud) 我正在使用Linux和C++.我有一个大小为210732字节的二进制文件,但使用seekg/tellg报告的大小为210728.
我从ls-la获得以下信息,即210732字节:
-rw-rw-r-- 1 pjs pjs 210732 Feb 17 10:25 output.osr
并使用以下代码片段,我得到210728:
std::ifstream handle;
handle.open("output.osr", std::ios::binary | std::ios::in);
handle.seekg(0, std::ios::end);
std::cout << "file size:" << static_cast<unsigned int>(handle.tellg()) << std::endl;
Run Code Online (Sandbox Code Playgroud)
所以我的代码关闭了4个字节.我已使用十六进制编辑器确认文件的大小是正确的.那么为什么我没有得到正确的尺寸?
我的回答:我认为这个问题是由于文件中有多个开放的fstream引起的.至少那似乎已经为我解决了.感谢所有帮助过的人.
我想要检索文件的大小,为此我以这种方式实现
(void)fseek(m_fp, 0, SEEK_END); // Set the file pointer to the end of the file
pFileSize = ftell(m_fp); // Get the file size
(void)fseek(m_fp, oldFilePos, SEEK_SET); // Put back the file pointer at the original location
Run Code Online (Sandbox Code Playgroud)
这对于out out是不可行的,并且是获取文件大小或检查文件是否包含数据的任何其他方式