8

我需要一种快速简便的方法来从标准 C++ 文件中获取字符串。我可以自己编写,但只想知道是否已经有标准的方式,用 C++ 编写。

如果您知道 Cocoa,则相当于:

NSString *string = [NSString stringWithContentsOfFile:file];
4

7 回答 7

17

我们可以做到,但这是一条很长的路线:

#include<fstream>
#include<iostream>
#include<iterator>
#include<string>

using namespace std;

int main()
{
    // The one-liner
    string fileContents(istreambuf_iterator<char>(ifstream("filename.txt")), istreambuf_iterator<char>());

    // Check result
    cout << fileContents;
}

编辑:使用“istreambuf_iterator”而不是“istream_iterator”

于 2008-09-26T00:31:17.543 回答
11

几乎可以使用 istream_iterator(3 行!)

#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    ifstream file("filename.txt");
    string fileContents;

    copy(istreambuf_iterator<char>(file),
              istreambuf_iterator<char>(),
              back_inserter(fileContents));
}

已编辑 - 摆脱了中间字符串流,现在直接复制到字符串中,现在使用忽略空格的 istreambuf_iterator(感谢 Martin York 的评论)。

于 2008-09-25T23:00:44.703 回答
3

标准 C++ 库不提供执行此操作的函数。

于 2008-09-25T22:54:23.267 回答
2

我能做的最好是5行:

#include <fstream>
#include <vector>
using namespace std;

ifstream f("filename.txt");
f.seekg(0, ios::end);
vector<char> buffer(f.tellg());
f.seekg(0, ios::beg);
f.read(&buffer[0], buffer.size());
于 2008-09-25T23:00:11.943 回答
2

怎么样:

#include <fstream>
#include <sstream>
#include <iostream>

using namespace std;

int main( void )
{
  stringstream os(stringstream::out);
  os << ifstream("filename.txt").rdbuf();
  string s(os.str());
  cout << s << endl;
}
于 2008-09-25T23:34:59.940 回答
0

如果您按照以下方式进行操作(但正确地包装好与下面不同),您可以读取文件而不必担心文件中的 0x1A 字节(例如)会缩短文件的读取时间。先前建议的方法将阻塞文件中的 0x1A(例如)。


#include <iostream>
#include <cstdio>
#include <vector>
#include <cstdlib>
using namespace std;

int main() {
    FILE* in = fopen("filename.txt", "rb");
    if (in == NULL) {
        return EXIT_FAILURE;
    }
    if (fseek(in, 0, SEEK_END) != 0) {
        fclose(in);
        return EXIT_FAILURE;
    }
    const long filesize = ftell(in);
    if (filesize == -1) {
        fclose(in);
        return EXIT_FAILURE;
    }
    vector<unsigned char> buffer(filesize);
    if (fseek(in, 0, SEEK_SET) != 0 || fread(&buffer[0], sizeof(buffer[0]), buffer.size(), in) != buffer.size() || ferror(in) != 0) {
        fclose(in);
        return EXIT_FAILURE;
    }
    fclose(in);
}

但是,是的,它不是一个已经实现的 1-liner。

编辑: 0x1A 不是一个很好的例子,因为 ios_base::binary 将涵盖这一点。然而,即使这样,当使用 .read() 一次性读取 png 文件时,C++ 流也经常给我带来麻烦。使用 C 方式效果更好。只是想不起一个很好的例子来说明原因。可能是在循环中以块的形式对二进制文件进行 .read() 处理,而这可能是 C++ 流的问题。所以,无视这个帖子。

于 2008-09-26T00:24:08.420 回答
0
std::string temp, file; std::ifstream if(filename); while(getline(if, temp)) file += temp;

这不是一个简短的或单一的语句行,但它是一个行,它真的没那么糟糕。

于 2010-08-30T10:51:11.310 回答