C++ 中的 Infile 句柄 (Perl 中的 __DATA__)
C++ 是否可以通过文件句柄访问文件内数据? 例如,Perl 中的典型习惯用法是:
while (<DATA>) {
chomp;
# do sth with $_
}
__DATA__
Foo
Bar
在 C++ 中如何做到这一点?
Does C++ have access to infile data through a filehandle? For example the typical idiom in Perl is:
while (<DATA>) {
chomp;
# do sth with $_
}
__DATA__
Foo
Bar
What's the way to do that in C++ ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的意思是在程序中包含该文件?
不,C++ 做不到这一点。 与 Perl 的方式不同。 有许多工具可以获取二进制或文本文件并将它们打包为 C/C++ 源代码。 它们最终只是作为一个全局数组。
我总是发现有用的一件事是能够打开随机内存作为文件句柄,这与您似乎要求的类似。 在标准 C++ 中,这可以通过 istringstream 类来完成,该类具有与 ifstream 相同的接口。
但你的问题的上下文可能意味着有更好的方法来完成你在 C/C++ 中的想法。 需要更多信息。
You mean including the file inside the program?
No, C++ can't do that. Not in the same way as Perl. There are many tools that will take binary or text files and package them as C/C++ source code. They just end up as a global array.
One thing I always found useful is the ability to open random memory as a file handle, which is similar to what you appear to be asking. In standard C++ this might be accomplished with the istringstream class, which has the same interface as ifstream.
But the context of your question may imply that there's a better way to accomplish what you're thinking in C/C++. More information is needed.
我不会说这是惯用的,因为我从未在任何 C++ 代码中见过它,但您可以使用 C++ 字符串流和 C 预处理器字符串粘贴将多行字符串视为输入流:
I wouldn't say it's idiomatic as I've never seen it in any C++ code, but you can use C++ string stream and C pre-processor string pasting to treat a multi-line string as an input stream:
C++ 没有执行此操作的惯用方法。 请改用单独的数据文件。
根据您的平台,您可能希望使用资源来实现类似的结果,但这超出了 C++ 的范围。 特别是,要将资源存储在二进制文件中,您需要使用外部工具,并在代码中读取这些资源,您需要调用平台 API。 例如,在 Windows 下,有
LoadResource
函数(及相关)。
C++ has no idiomatic way of doing this. Use a separate data file instead.
Depending on your platform, you might want to use resources to achieve a similar result but this is beyond the scope of C++. In particular, to store the resources in the binary file you need to use external tools and to read these resources in your code you need to invoke platform API. For example under Windows, there's the
LoadResource
function (and related).