Reading a textfile on the web

A text file is hosted on the internet. www.a.com/b.txt

I want to read the file for input. How do I do this?
C++ does not have a built-in way of using the HTTP protocol. You'll want a HTTP library for that:

http://scumways.com/happyhttp/happyhttp.html
http://curl.haxx.se/libcurl/competitors.html

I haven't used any HTTP library yet, so I'm afraid I can't recommend or assist you in learning one. But the HappyHTTP library appears to be the simplest to use. (Site mentions it does not currently compile in Visual Studio.)
Last edited on
The most portable approach (which will likely become part of C++ in the next standard extension), is boost.asio

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
#include <boost/asio.hpp>
int main()
{
    boost::asio::ip::tcp::iostream s("www.a.com", "http");
    if(!s)
        std::cout << "Could not connect to www.a.com\n";
    s  << "GET /b.txt HTTP/1.0\r\n"
       << "Host: www.a.com\r\n"
       << "Accept: */*\r\n"
       << "Connection: close\r\n\r\n" ;
    for(std::string line; getline(s, line); )
         std::cout << line << '\n';
}


As you can see, it is a bit more low-level than you probably need (you have to write HTTP protocol by hand). If that's not what you want, do try out third-party HTTP libraries:
curl++: http://curlpp.org/
poco: http://pocoproject.org/
cpp-netlib: http://cpp-netlib.sourceforge.net/
Last edited on
Topic archived. No new replies allowed.