tags:

views:

415

answers:

3

Hi,

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++ ?

+5  A: 

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.

Dan Olson
If the data is in a static (module scope) string, then a stringstream could be used to read it.
Richard
+2  A: 

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).

Konrad Rudolph
+1  A: 

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:

#include <sstream>
#include <iostream>

using namespace std;

const string data = 
    "once upon a time, " \
    "a young lass called Goldilocks\n" \
    "went for a walk in the forest.\n";

int main ()
{
    istringstream in (data);

    for (string line; getline(in, line); ) 
        cout << line << endl;

    return 0;
}
Pete Kirkham
I think you should put the getline in the while condition itself. Your loop will currently print 'line' even when getline fails at the end of the string.
Kristo