Does the close method of ofstream also close the underlying handle - c++

On Windows platform, a file handle is got from calling CreateFile, and then the handle is used to initialize an ofstream object. A minimal example is as below:
#include"stdafx.h"
#include <tchar.h>
#include <iostream>
#include <fstream>
#include <windows.h>
#include <io.h>
#include <fcntl.h>
class CSV_writer {
public:
std::ofstream my_ofstream;
private:
HANDLE my_handle = INVALID_HANDLE_VALUE;
int file_descriptor = -1;
FILE * my_file = nullptr; //FILE type is actually a IO buff.
const static unsigned int fl = 256;
public:
explicit CSV_writer(const TCHAR * file_name_) {
//get current directory
TCHAR current_path[MAX_PATH];
GetCurrentDirectory(MAX_PATH, current_path);
TCHAR filename[fl]{ 0 };
_tcscat_s(filename, file_name_);
_tcscat_s(filename, _T(".csv"));
if (current_path[_tcslen(current_path) - 1] != _T('\\') && _tcslen(current_path) < MAX_PATH - 1) {
_tcscat_s(current_path, _T("\\"));
}
else {
throw std::exception("path length exceeding limit.");
}
if (_tcslen(current_path) + _tcslen(filename) + 1 < MAX_PATH) {
_tcscat_s(current_path, filename);
}
else {
//current path exceeds the max path length defined in MAX_PATH
throw std::exception("path length exceeding limit.");
}
this->my_handle = CreateFile(
current_path,
GENERIC_READ | GENERIC_WRITE, //access permit, both read and write
0, //cannot be shared and cannot be opened again until the handle to the file or device is closed
nullptr, //returned handle can not be inherited by child process
CREATE_ALWAYS, //always create a new file, overwrite old one if it exists
FILE_ATTRIBUTE_NORMAL,
nullptr
);
if (my_handle != INVALID_HANDLE_VALUE) {
int file_descriptor = _open_osfhandle((intptr_t)my_handle, _O_TEXT);
if (file_descriptor != -1) {
this->my_file = _fdopen(file_descriptor, "w");
if (this->my_file != nullptr) {
this->my_ofstream = std::ofstream(this->my_file);
}
}
}
}
~CSV_writer() {
// Closes stream, file, file_descriptor, and file_handle.
this->my_ofstream.flush();
this->my_ofstream.close();
this->my_file = nullptr;
this->file_descriptor = -1;
this->my_handle = INVALID_HANDLE_VALUE;
}
};
int main(int argc, char* argv[])
{
CSV_writer csv_writer(L"memory_layout");
csv_writer.my_ofstream << "Type,\t" << "Size,\t" << "Offset,\t" << "Address\n";
return 0;
}
My question is, after calling "my_ofstream.close()" afterwards, will the underlying file handle also released? Or I have to call Windows API CloseHandle() manually after calling close()?
Update: to those who say that there is no constructor of ofstream taking FILE*, actually there is, kind of,

I hope you're already aware that the constructor you are using:
std::ofstream(FILE * fp)
is a non-standard, undocumented Microsoft extension, unguaranteed even by Microsoft.
In that case, Microsoft does not promise you even that:
int fd = ...;
...
FILE * fp = _fdopen(fd, "w");
...
std::osftream ofs(fp);
...
ofs.close();
will do fclose(fp) - never mind _close(fd).
If however you take it as given that ofs.close() does fclose(fp) - and evidently you do - then Microsoft
does promise you that it will also _close(fd). From the documentation
Remarks
...
File descriptors passed into _fdopen are owned by the returned FILE * stream.
If _fdopen is successful, do not call _close on the file descriptor.
Calling fclose on the returned FILE * also closes the file descriptor.
(My emphasis.)

Related

Can't read USN journal non-stop

My goal is to read write operations from a chosen drive (usually C), using USN journal.
In the next code I've written, I made a small class that processes USN records by using DeviceIoControl
with the FSCTL_QUERY_USN_JOURNAL and FSCTL_ENUM_USN_DATA codes.
#include "stdafx.h"
#include <stdio.h>
#include <assert.h>
#include <vector>
#include <system_error>
#include <Windows.h>
[[noreturn]] void throw_system_error(int error_code) {
throw std::system_error(error_code, std::system_category());
}
class usn_journal {
private:
HANDLE m_drive_handle;
std::vector<uint8_t> m_buffer;
USN_JOURNAL_DATA* m_usn_journal_data;
USN m_next_usn_record_id;
public:
usn_journal(const wchar_t* driver_name) {
m_next_usn_record_id = 0;
m_drive_handle = ::CreateFileW(
driver_name,
GENERIC_READ,
FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr,
OPEN_ALWAYS,
FILE_FLAG_NO_BUFFERING,
nullptr);
if (m_drive_handle == INVALID_HANDLE_VALUE) {
throw_system_error(::GetLastError());
}
m_buffer.resize(1024 * 1024);
}
~usn_journal() {
::CloseHandle(m_drive_handle);
}
void refresh_jounral() {
assert(m_buffer.size() == 1024 * 1024);
DWORD buffer_count = 0;
if (!DeviceIoControl(
m_drive_handle,
FSCTL_QUERY_USN_JOURNAL,
nullptr,
0,
m_buffer.data(),
m_buffer.size(),
&buffer_count,
nullptr)) {
throw_system_error(::GetLastError());
}
m_usn_journal_data =
reinterpret_cast<decltype(m_usn_journal_data)>(m_buffer.data());
}
void process_entries() {
DWORD bytes_read = 0;
MFT_ENUM_DATA_V0 mft_enum_data = {};
mft_enum_data.StartFileReferenceNumber = m_next_usn_record_id;
mft_enum_data.LowUsn = 0;
mft_enum_data.HighUsn = m_usn_journal_data->MaxUsn;
assert(m_buffer.size() == 1024 * 1024);
for (;;){
auto buffer = m_buffer.data();
if (!DeviceIoControl(
m_drive_handle,
FSCTL_ENUM_USN_DATA,
&mft_enum_data,
sizeof(mft_enum_data),
buffer,
m_buffer.size(),
&bytes_read,
nullptr)){
auto error_code = ::GetLastError();
if (error_code == ERROR_HANDLE_EOF) {
return;
}
else {
throw_system_error(::GetLastError());
}
}
m_next_usn_record_id = *reinterpret_cast<USN*>(buffer);
auto buffer_real_begin = buffer + sizeof(USN);
auto usn_cursor = reinterpret_cast<USN_RECORD*>(buffer_real_begin);
int64_t total_usn_buffer_number = bytes_read - sizeof(USN);
while (total_usn_buffer_number >= 0){
total_usn_buffer_number -= usn_cursor->RecordLength;
buffer = reinterpret_cast<uint8_t*>(usn_cursor) + usn_cursor->RecordLength;
usn_cursor = reinterpret_cast<USN_RECORD*>(usn_cursor);
if (usn_cursor->Reason != 0) {
printf("%d\n", (int)usn_cursor->Reason);
}
}
mft_enum_data.StartFileReferenceNumber = m_next_usn_record_id;
}
}
};
int main(int argc, char ** argv){
usn_journal my_journal(L"\\\\?\\c:");
while (true) {
my_journal.refresh_jounral();
my_journal.process_entries();
}
return 0;
}
Here is my problem, after a while, the records are exhausted, and calling DeviceIoControl and FSCTL_ENUM_USN_DATA
DeviceIoControl fails and the error code I get is ERROR_HANDLE_EOF, even if I refresh the journal, I get the same error.
I want to be able to stream any new USN record, and handle write events. I know for sure it's possible as there are
third party tools which present USN records non-stop.
how can reproduce this state of non-stop streaming?

C++ Feeding strings from a text document as arguments

Is there a way to feed strings from a text document directly as arguments? Preferably without saving them?
I have a killProcessByName method that is expecting an argument so I was wondering if it is possible to read the first line from my text document, copy it then send it as an argument? Then move on to the next line, preform the same thing and repeat the process until there are no words left in the document?
Example of my list:
Apples.exe
Blueberries.exe
Watermelon.exe
Oranges.exe
...
The method I'm targeting
void killProcessByName(const char *filename)
{
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
PROCESSENTRY32 pEntry;
pEntry.dwSize = sizeof (pEntry);
BOOL hRes = Process32First(hSnapShot, &pEntry);
while (hRes)
{
if (strcasecmp(pEntry.szExeFile, filename) == 0)
{
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0,
(DWORD) pEntry.th32ProcessID);
if (hProcess != NULL)
{
TerminateProcess(hProcess, 9);
CloseHandle(hProcess);
}
}
hRes = Process32Next(hSnapShot, &pEntry);
}
CloseHandle(hSnapShot);
}
#include <iostream> // std::cout, std::endl
#include <fstream> // std::ifstream
using namespace std;
int main()
{
// open your file
ifstream input_file("test.txt");
// create variables
string name;
// while there are entries
while(input_file >> name)
{
killProcessByName(name.c_str());
}
// close the file
input_file.close();
return 0;
}

How can I copy and paste a file in Windows using C++?

I have googled this, but I am still confused about how to use it. I am making a file manager, and I want to be able t o copy and paste a file into a new directory. I know to copy I need to use file.copy(), but I am not sure how to implement it into my code.
I would like to do this using fstream.
If you are using the Win32 API then consider looking into the functions CopyFile or CopyFileEx.
You can use the first in a way similar to the following:
CopyFile( szFilePath.c_str(), szCopyPath.c_str(), FALSE );
This will copy the file found at the contents of szFilePath to the contents of szCopyPath, and will return FALSE if the copy was unsuccessful. To find out more about why the function failed you can use the GetLastError() function and then look up the error codes in the Microsoft Documentation.
void copyFile(const std::string &from, const std::string &to)
{
std::ifstream is(from, ios::in | ios::binary);
std::ofstream os(to, ios::out | ios::binary);
std::copy(std::istream_iterator(is), std::istream_iterator(),
std::ostream_iterator(os));
}
Here is my implementation to copy a file, you should take a look at boost filesystem since that library will be part of the standard c++ library.
#include <fstream>
#include <memory>
//C++98 implementation, this function returns true if the copy was successful, false otherwise.
bool copy_file(const char* From, const char* To, std::size_t MaxBufferSize = 1048576)
{
std::ifstream is(From, std::ios_base::binary);
std::ofstream os(To, std::ios_base::binary);
std::pair<char*,std::ptrdiff_t> buffer;
buffer = std::get_temporary_buffer<char>(MaxBufferSize);
//Note that exception() == 0 in both file streams,
//so you will not have a memory leak in case of fail.
while(is.good() and os)
{
is.read(buffer.first, buffer.second);
os.write(buffer.first, is.gcount());
}
std::return_temporary_buffer(buffer.first);
if(os.fail()) return false;
if(is.eof()) return true;
return false;
}
#include <iostream>
int main()
{
bool CopyResult = copy_file("test.in","test.out");
std::boolalpha(std::cout);
std::cout << "Could it copy the file? " << CopyResult << '\n';
}
The answer of Nisarg looks nice, but that solution is slow.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa363851(v=vs.85).aspx
I don't know what you mean by copy and paste a file; that makes no sense. You can copy a file to another location and I assume that's what you are asking about.
In native C++, you can use:
The CopyFile function : http://msdn.microsoft.com/en-us/library/windows/desktop/aa363851%28v=vs.85%29.aspx
CopyFileEx function for more advanced options like progress notifications. http://msdn.microsoft.com/en-us/library/windows/desktop/aa363852%28v=vs.85%29.aspx
Using C makes C++ projects more portable. Here my sample code is a reference for you.
int file_copy(char* fn_dst, char* fn_src) {
FILE* pf = NULL;
char* buf = NULL;
int len = 0;
//get length of file src
pf = fopen(fn_src, "r");
if (pf == NULL) {
printf("[%s]Failed to fopen:%s\n", __func__, fn_src);
return -1;
}
fseek(pf, 0, SEEK_END);
len = ftell(pf);
fclose(pf);
//allocate buf
buf = (char*)malloc(len);
if (buf == NULL) {
printf("[%s]Failed to malloc\n", __func__);
return -1;
}
memset(buf, 0, len);
//read from file src
pf = fopen(fn_src, "rb");
if (pf == NULL) {
printf("[%s]Failed to fopen:%s\n", __func__, fn_src);
return -1;
}
fread(buf, 1, len, pf);
fclose(pf);
//write into file dst
pf = fopen(fn_dst, "wb+");
if (pf == NULL) {
printf("[%s]Failed to fopen:%s\n", __func__, fn_dst);
return -1;
}
fwrite(buf, 1, len, pf);
fclose(pf);
if (buf)
free(buf);
return 0;
}
System::IO::File::Copy("Old Path", "New Path");

Memory leak when read from file

I'm trying to read data from XML file and store every element ("< some data/>") in vector container vector<TCHAR*> , why the Task Manager shows the memory usage much greater than vector size(~80mb instead of ~59mb) :
#define _UNICODE
#include<tchar.h>
#include<iostream>
#include<windows.h>
#include<vector>
using namespace std;
HANDLE hFile;
HANDLE hThread;
vector<TCHAR*> tokens;
DWORD tokensSize;
DWORD WINAPI Thread(LPVOID lpVoid);
void main()
{
tokensSize = 0;
hFile = CreateFile("db.xml",GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if(hFile == INVALID_HANDLE_VALUE) {
cout<<"CreateFile Error # "<<GetLastError()<<endl;
}
DWORD fileSize = GetFileSize(hFile,NULL);
cout<<"fileSize = "<<fileSize<<" bytes = "<<fileSize/1024/1024<<" mb"<<endl;
TCHAR* buffer = new TCHAR[fileSize / sizeof(TCHAR) + 1];
ZeroMemory(buffer,fileSize);
DWORD bytesRead;
if(!ReadFile(hFile,buffer,fileSize,&bytesRead,NULL)){
cout<<"ReadFile Error # "<<GetLastError()<<endl;
}
CloseHandle(hFile);
hThread = CreateThread(NULL,0,Thread,(LPVOID)buffer,0,NULL);
WaitForSingleObject(hThread,INFINITE);
for(int i=0;i<tokens.size();i++)
tokensSize+=(_tcslen(tokens[i])+1)*sizeof(TCHAR);
cout<<"vector size = "<<tokensSize<<" bytes = "<<tokensSize/1024/1024<<" mb"<<endl;
cin.get();
}
DWORD WINAPI Thread(LPVOID lpVoid)
{
wstring entireDB = (TCHAR*)lpVoid;
delete[]lpVoid;
wstring currentElement;
wstring::size_type lastPos = 0;
wstring::size_type next;
next = entireDB.find(_T(">"),lastPos);
TCHAR* szStr;
do
{
currentElement = entireDB.substr(lastPos,next+1-lastPos);
szStr = new TCHAR[currentElement.length()+1];
_tcscpy(szStr,currentElement.c_str());
tokens.push_back(szStr);
lastPos = next+1;
next = entireDB.find(_T(">"),lastPos);
}
while(next != wstring::npos);
entireDB.clear();
return 0;
}
OUTPUT:~
fileSize = 57mb
vectorSize = 58mb
but the TaskManager shows ~ 81mb.
What am I doing wrong?
THNX!
First, as Aesthete as pointed out, you never clear the token vector once you're finished with it. This should be done, or change the token vector to utilize self-cleaning content like std::string or std::wstring.
Which brings me to the side-by-side below. Please review this against your existing code. There are a number of changes you'll want to compare. The one you will likely not see until you cmopile+run is the memory footprint difference, which may surprise you.
Major Changes
Global tokens is now a vector of std::wstring rather than raw wchar_t pointers
Uses MultiByteToWideChar to translate the input file.
Allocates a std::wstring dynamically as the thread parameter. This removes one full copy of the file image. The thread is responsible for deleteing the wstring once finished parsing the content.
Uses _beginthreadex() for starting the thread. The fundamental reason for this is because of the C/C++ runtime usage. In the past the runtime sets up various thread-local-storage that must be properly cleaned, and are so when using _beginthreadex(). It is almost identical to CreateThread(), but honestly I look forward to the day when MS has their stuff together and gives us std::thread officially like the rest of the civilized world.
Minor/Meaningless Changes
Global variables are brought to local scope where appropriate. this means the only real global now is the tokens vector.
The thread procedure now pushes substrings straight to the tokens vector.
uses argv[1] for the filename (easy to debug that way, no other special reason). can be changed back to your hard-coded filename as needed.
I hope this gives you some ideas on cleaning this up, and more importantly, how yoy can do almost the entire task you're given without having to go new and delete nuts.
Notes: this does NOT check the input file for a byte-order-mark. I'm taking it on faith that your claim it is UTF8 is straight-up and doesn't have a BOM at the file beginning. If your input file does have a BOM, you need to adjust the code that reads the file in to account for this.
#include <windows.h>
#include <tchar.h>
#include <process.h>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// global map of tokens
vector<wstring> tokens;
// format required by _beginthreadex()
unsigned int _stdcall ThreadProc(void *p);
int main(int argc, char *argv[])
{
HANDLE hThread = NULL;
std::string xml;
std::wstring* pwstr = NULL;
// check early exit
if (argc != 2)
{
cout << "Usage: " << argv[0] << " filename" << endl;
return EXIT_FAILURE;
}
// use runtime library for reading the file content. the WIN32 CreateFile
// API is required for some things, but not for general file ops.
HANDLE hFile = CreateFileA(argv[1], GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
DWORD dwFileSize = GetFileSize(hFile, NULL);
if (dwFileSize > 0)
{
// allocate a string large enough for the whole file.
std::string xml(dwFileSize, 0);
DWORD bytesRead = 0;
if (ReadFile(hFile, &xml.at(0), dwFileSize, &bytesRead, NULL) && (bytesRead == dwFileSize))
{
// invoke MB2WC to determine wide-char requirements
int ires = MultiByteToWideChar(CP_UTF8, 0, xml.c_str(), -1, NULL, 0);
if (ires > 0)
{
// allocate a wstring for our thread parameter.
pwstr = new wstring(ires, 0);
MultiByteToWideChar(CP_UTF8, 0, xml.c_str(), -1, &pwstr->at(0), ires);
// launch thread. it own the wstring we're sending, including cleanup.
hThread = (HANDLE)_beginthreadex(NULL, 0, ThreadProc, pwstr, 0, NULL);
}
}
}
// release the file handle
CloseHandle(hFile);
}
// wait for potential thread
if (hThread != NULL)
{
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
}
// report space taken by tokens
size_t tokensSize = 0;
for (vector<wstring>::const_iterator it = tokens.begin(); it != tokens.end(); ++it)
tokensSize += it->size()+1;
cout << "tokens count = " << tokens.size() << endl
<< "tokens size = "<< tokensSize <<" bytes" << endl;
cin.get();
}
// our thread parameter is a dynamic-allocated wstring.
unsigned int _stdcall ThreadProc(void *p)
{
// early exit on null insertion
if (p == NULL)
return EXIT_FAILURE;
// use string passed to us.
wstring* pEntireDB = static_cast<wstring*>(p);
wstring::size_type last = 0;
wstring::size_type next = pEntireDB->find(L'>',last);
while(next != wstring::npos)
{
tokens.push_back(pEntireDB->substr(last, next-last+1));
last = next+1;
next = pEntireDB->find(L'>', last);
}
// delete the wstring (no longer needed)
delete pEntireDB;
return EXIT_SUCCESS;
}
You allocate memory here, in the do-while loop:
szStr = new TCHAR[currentElement.length()+1];
And you never release it with the delete operator

How to download an image from an URL to a local dir?

I'm using C++ without .NET on Win32, how can I download an image over HTTP from a website without having to re-invent the wheel? Is there an API or library that provides a single function to do this?
http://mywebsite/file.imgext --> C:\path\to\dir\file.imgext
WinInet APIs are easier than you think
Here is a complete win32 console program. Can be built with with VS 2010 Express and down loading windows SDK to get WinInit.
// imaged.cpp : Defines the entry point for the console application.
//
// Copy file from internet onto local file
// Uses Wininet API
// program takes 1 mandatory command line argument - URL string
// it downloads ito the current directory, or whatever is passed
// as the second parameter to DownloadURLImage.
// optional parameter, the name of the file (excluding path), by default it uses the
// filename from the URL string.
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <WinInet.h> // from SDK
#include "string.h"
//#include<TCHAR.H>
//#include "Tchar.h"
using namespace std ;
int convertURLtofname (TCHAR * szURL, TCHAR * szname )
// extract the filename from the URL
{
char aszfilename [100];
HRESULT result;
char achar[3], aszURL [100];
size_t nchars, i, j;
int fresult;
fresult = 0;
nchars= _tcslen(szURL);
i= nchars -1;
while ((i > 0) && (szURL[i] != '/') && (szURL[i] != '\\')) {i--;}
j= 0; i++;
while (i < nchars) { szname [j++]= szURL[i++]; }
szname[j]=_T('\0');
// wcstombs ( aszfilename, szname, 100 );
// cout << aszfilename << endl;
//----------------------------------------------
return fresult ;
}
int determinepathfilename (TCHAR * szURL, TCHAR * szpath, TCHAR * szname, TCHAR * szpathfilename)
{
// use path and filename when supplied. If filename (e.g. funkypic.jpg) is not supplied, then the
// filename will be extracted from the last part of the URL
int result ;
result= 0;
TCHAR szname_copy [100] ;
if ((szname == NULL) || (szname[0] == '\0'))
convertURLtofname (szURL, szname_copy);
else
_tcscpy (szname_copy, szname);
if ((szpath == NULL) || (szpath[0] == '\0'))
_tcscpy (szpathfilename, szname_copy);
else
{
_tcscpy (szpathfilename, szpath);
_tcscat (szpathfilename, szname_copy);
}
return result ;
}
bool GetFile (HINTERNET hOpen, // Handle from InternetOpen()
TCHAR *szURL, // Full URL
TCHAR * szpath,
TCHAR * szname)
{
DWORD dwSize;
TCHAR szHead[15];
BYTE * szTemp[1024];
HINTERNET hConnect;
FILE * pFile;
TCHAR szpathfilename [100] ;
szHead[0] = '\0';
if ( !(hConnect = InternetOpenUrl( hOpen, szURL, szHead, 15, INTERNET_FLAG_DONT_CACHE, 0)))
{
std::cout << "Error: InternetOpenUrl" << std::endl;
return 0;
}
determinepathfilename (szURL, szpath, szname, szpathfilename);
if ( !(pFile = _tfopen (szpathfilename, _T("wb") ) ) )
{
std::cerr << "Error _tfopen" << std::endl;
return false;
}
do
{
// Keep copying in 1024 bytes chunks, while file has any data left.
// Note: bigger buffer will greatly improve performance.
if (!InternetReadFile (hConnect, szTemp, 1024, &dwSize) )
{
fclose (pFile);
std::cerr << "Error InternetReadFile" << std::endl;
return FALSE;
}
if (!dwSize)
break; // Condition of dwSize=0 indicate EOF. Stop.
else
fwrite(szTemp, sizeof (BYTE), dwSize , pFile);
} // do
while (TRUE);
fflush (pFile);
fclose (pFile);
return TRUE;
}
int DownloadURLImage (TCHAR * szURL, TCHAR * szpath, TCHAR * szname)
{ int result ;
HINTERNET hInternet;
result= 0;
hInternet= InternetOpen (_T("imaged"),
INTERNET_OPEN_TYPE_DIRECT, //__in DWORD dwAccessType
NULL, //__in LPCTSTR lpszProxyName,
NULL, //__in LPCTSTR lpszProxyBypass,
NULL //_in DWORD dwFlags
);
GetFile (hInternet, szURL, szpath, szname) ;
InternetCloseHandle(hInternet);
return result ;
}
int _tmain(int argc, _TCHAR* argv[])
{
if (argc == 2)
{
DownloadURLImage (argv[1], NULL, NULL);
//DownloadURLImage (argv[1], _T"C:/", NULL);
}
else if (argc == 3)
{
DownloadURLImage (argv[1], NULL, argv[2]);
//DownloadURLImage (argv[1], _T"C:/", argv[2]);
}
else
{
cout << "Usage: imaged <image URL>" << endl ;
}
system("pause") ;
return 0;
}
You could use cURLpp
I havn't used it yet, but example20 looks like it could solve your problem.
If you want an EASY solution, use this amazingly simple one liner:
system("C:\\Path\\To\\Wget\\wget.exe http://pixelcaster.com/yosemite/webcams/ahwahnee2.jpg -O C:\\Users\\Me\\Desktop\\ahwahnee2.jpg");
With wget for windows
choco install wget
See chocolatey.org
Use Windows Http Services API.
You could use the WinInet or WinHTTP classes in C++. These are native Win32 APIs the abstract some of the work of getting sending and receiving files from the Internet.
I've used WinInet with great success to do just what you're trying to do.
If starting a new process is ok, you could have a look at WGET. (And even if not, the sources are available; you can look there to see how it's been implemented.)
Using POCO for this now. :-)