son*_*phi 76 c++ string file-io
在像Perl这样的脚本语言中,可以一次将文件读入变量.
open(FILEHANDLE,$file);
$content=<FILEHANDLE>;
Run Code Online (Sandbox Code Playgroud)
在C++中最有效的方法是什么?
Mai*_*ann 163
像这样:
#include <fstream>
#include <string>
int main(int argc, char** argv)
{
std::ifstream ifs("myfile.txt");
std::string content( (std::istreambuf_iterator<char>(ifs) ),
(std::istreambuf_iterator<char>() ) );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
该声明
std::string content( (std::istreambuf_iterator<char>(ifs) ),
(std::istreambuf_iterator<char>() ) );
Run Code Online (Sandbox Code Playgroud)
可以拆分成
std::string content;
content.assign( (std::istreambuf_iterator<char>(ifs) ),
(std::istreambuf_iterator<char>() ) );
Run Code Online (Sandbox Code Playgroud)
如果您只想覆盖现有std :: string变量的值,这将非常有用.
Cos*_*ert 39
最有效但不是C++的方式是:
FILE* f = fopen(filename, "r");
// Determine file size
fseek(f, 0, SEEK_END);
size_t size = ftell(f);
char* where = new char[size];
rewind(f);
fread(where, sizeof(char), size, f);
delete[] where;
Run Code Online (Sandbox Code Playgroud)
#编辑 - 2刚刚测试了std::filebuf变体.看起来它可以被称为最好的C++的办法,即使它并不完全是C++的做法,但更多的是包装.无论如何,这里的代码块几乎和普通的C一样快.
std::ifstream file(filename, std::ios::binary);
std::streambuf* raw_buffer = file.rdbuf();
char* block = new char[size];
raw_buffer->sgetn(block, size);
delete[] block;
Run Code Online (Sandbox Code Playgroud)
我在这里做了一个快速的基准测试,结果如下.在使用适当的(和)模式读取65536K二进制文件时进行测试.std::ios:binaryrb
[==========] Running 3 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 4 tests from IO
[ RUN ] IO.C_Kotti
[ OK ] IO.C_Kotti (78 ms)
[ RUN ] IO.CPP_Nikko
[ OK ] IO.CPP_Nikko (106 ms)
[ RUN ] IO.CPP_Beckmann
[ OK ] IO.CPP_Beckmann (1891 ms)
[ RUN ] IO.CPP_Neil
[ OK ] IO.CPP_Neil (234 ms)
[----------] 4 tests from IO (2309 ms total)
[----------] Global test environment tear-down
[==========] 4 tests from 1 test case ran. (2309 ms total)
[ PASSED ] 4 tests.
Run Code Online (Sandbox Code Playgroud)
Mar*_*ork 12
最有效的方法是创建一个正确大小的缓冲区,然后将文件读入缓冲区.
#include <fstream>
#include <vector>
int main()
{
std::ifstream file("Plop");
if (file)
{
/*
* Get the size of the file
*/
file.seekg(0,std::ios::end);
std::streampos length = file.tellg();
file.seekg(0,std::ios::beg);
/*
* Use a vector as the buffer.
* It is exception safe and will be tidied up correctly.
* This constructor creates a buffer of the correct length.
* Because char is a POD data type it is not initialized.
*
* Then read the whole file into the buffer.
*/
std::vector<char> buffer(length);
file.read(&buffer[0],length);
}
}
Run Code Online (Sandbox Code Playgroud)
\0文本文件中应该没有.
#include<iostream>
#include<fstream>
using namespace std;
int main(){
fstream f(FILENAME, fstream::in );
string s;
getline( f, s, '\0');
cout << s << endl;
f.close();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
170328 次 |
| 最近记录: |