Download file to temp dir in C++ - c++

I'm trying to download a file from the internet to my temp directory.
This is what I have so far:
HRESULT hr;
LPCTSTR Url = _T("linkhere"), File = _T("C:\\test.exe");
hr = URLDownloadToFile (0, Url, File, 0, 0);
This is working fine.
How do I save the file to the temp directory (using GetTempPath)

Since the directory that's used to store temporary files is configurable, you shouldn't hardcode its path into the application. Instead, use GetTempPath() to ask for the path and then use the result as a prefix, meaning you can simply append "temp.exe" to it.
(Btw, you can use "/" instead "\", since constantly having to escape backslashes is both tedious and error prone. For example, instead of "some\random\path\", you write "some/random/path/").

Related

When my program runs automatically at startup, having trouble append text to file. Why?

I made a program that runs automatically at startup, but my program does not perform the task of append text to the file when it runs automatically.
Here example code:
#include <Windows.h>
#include <fstream>
#include <iostream>
void AutoRun() {
LONG key;
std::string FP;
char re[MAX_PATH];
FP = std::string(re, GetModuleFileNameA(NULL, re, MAX_PATH));
HKEY hkey;
key = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\Currentversion\\Run", 0, KEY_WRITE, &hkey);
if (key == ERROR_SUCCESS)
{
std::cout << "paketi yüklüyoruzzz";
key = RegSetValueExA(hkey, "testzort", 0, REG_SZ, (BYTE*)FP.c_str(), strlen(FP.c_str()));
RegCloseKey(hkey);
}
else {
std::cout << "Maga mapket müklenemedi:(: " << key;
}
}
int main(){
// open output file in append mode
const char* output_filename = "testing.log";
std::cout << "Logging output to " << output_filename << std::endl;
output_file.open(output_filename, std::ios_base::app);
AutoRun();
output_file << "zozozort\n";
}
When I restart my computer after execute this code, not add my file like:
zozozort
zozozort
What is the problem ?
NOTE: For the first time to run the regedit api, I ran the program with administrator mode when starting
First off, consider using HKEY_CURRENT_USER instead of HKEY_LOCAL_MACHINE (unless you really want all users of your machine running your app). And consider using KEY_SET_VALUE instead of KEY_WRITE (which includes rights you don't need in this code). This will reduce the need for your code to run as an admin when setting up the auto-run.
In any case, when calling RegSetValueEx(), you are setting the data size to strlen(FP.c_str()), which is wrong, as RegSetValueEx() requires the null terminator to be included in the data size:
If the data is of type REG_SZ, REG_EXPAND_SZ, or REG_MULTI_SZ, cbData must include the size of the terminating null character or characters.
So, use strlen(FP.c_str())+1 instead, or better FP.size()+1.
That being said, your app is opening the text file using a relative path, so its location is relative to the app's current working directory, which you don't know what it is when your app is started (you can use GetCurrentDirectory() to determine that). Just because the text file is in the same folder as your app doesn't mean the working directory points to your app's folder. Always use absolute paths when creating/opening files.
If you were using CreateFile() instead of (o)fstream (BTW, where is your output_file variable declared?) to create/open the file, then you could use GetFinalPathNameByHandle() to determine its actual full path, so you can see if it is what you are expecting.
If your really want to create/open the text file in your app's folder, you already know how to get the app's full file path from GetModuleFileName(), so simply replace the filename portion after the last '\' character with your text file's name, and then use that full path to create/open the file. Just make sure your app is not running in a folder that denies write access to non-admins, such as Program Files.
You really should be writing the text file into a folder that is guaranteed to be accessible to the calling user (preferably within their own profile), instead of in the app's folder. For instance, get a user-accessible folder path via either:
SHGetFolderPath(), specifying something like CSIDL_(LOCAL_|COMMON_)APPDATA, CSIDL_DESKTOPDIRECTORY, CSIDL_MYDOCUMENTS, etc.
SHGetKnownFolderPath(), specifying something like FOLDERID_(Roaming|Local)AppData, FOLDERID_ProgramData, FOLDERID_Desktop, FOLDERID_Documents, etc.
Then, create your own subfolder underneath that folder, and create the file inside that subfolder.

GetPrivateprofilestring does not get an ini file in current directory

Well, the title say which is my problem
my .cpp code is:
GetPrivateProfileString("Server","MainDns","ServerDns",
g_DataBaseDns,sizeof(g_DataBaseDns),".\\Server.ini");
when I use:
GetPrivateProfileString("Server","MainDns","ServerDns",
g_DataBaseDns,sizeof(g_DataBaseDns),"..\\Server.ini");
and Put the ini file in the back folder: works normally!
What am I doing wrong?
You need to first call GetFullPathName() to obtain an absolute path, which is required according to the documentation for GetPrivateProfileString():
The name of the initialization file. If this parameter does not contain a full path to the file, the system searches for the file in the Windows directory.
For example:
TCHAR sAbsolutePathBuffer[2048] = _T("");
if (GetFullPathName(TEXT("Server.ini"), sizeof(sAbsolutePathBuffer)/sizeof(TCHAR), sAbsolutePathBuffer, NULL))
{
GetPrivateProfileString(TEXT("Server"), TEXT("MainDns"), TEXT("ServerDns"),
g_DataBaseDns, sizeof(g_DataBaseDns), sAbsolutePathBuffer);
}

c++ GetPrivateProfileString read ini file from current directory

I'm creating a dll on c++. It is a Visual Studio project. The dll reads some data from ini file. I have decided to use GetPrivateProfileString function. It works almost completely. It does not see file in current directory. How can I provide this parameter (variable called path)?
How can I pass last parameter (path)
Code:
LPCTSTR path = L"\\test.ini";
TCHAR protocolChar[32];
int a = GetPrivateProfileString(_T("Connection"), _T("Protocol"), _T(""), protocolChar, 32, path);
String from test.ini:
[Connection]
Protocol = HTTP
I also tried this:
LPCTSTR path = L"test.ini";
But it did not help me
LPCTSTR path = _T(".\\test.ini");
. symbolises current directory. Hope this will work for you.
WCHAR cfg_IniName[256];
GetCurrentDirectory (MAX_PATH, cfg_IniName );
wcscat ( cfg_IniName, L"\\test.ini" );
way to get full path

Unexpected behavior while opening escaped file:/// URL in IE

I could swear to god that the code below used to work a week ago. I can tell that because the software I develop depends on it.
This code chunk is supposed to open an html page from a local HDD using IE:
(These strings are not hardcoded in my actual example. What it does is this -- it escapes the path to the local html file and adds file:/// in front.)
LPCTSTR m_strBrowser = L"C:\\Program Files (x86)\\Internet Explorer\\iexplore.exe";
LPCTSTR addr2 = L"\"file:///C%3a%5cUsers%5cUserName%5cAppData%5cLocal%5cTemp%5cReport_View.htm\"";
ShellExecute(hMain, NULL, m_strBrowser, addr2, NULL, SW_SHOWNORMAL);
But what I get when I test it today is just the home page in IE.
Any idea what is wrong here?
PS. The Report_View.htm file exists in the file system.
PS2. If I copy and paste the escaped URL into Chrome or FF, it opens just fine.
Well, evidently they made some changes to the IE and now the file protocol URL can no longer contain arbitrary escaping. From my experience, the only way to make it work with IE is by getting the file protocol path by calling the UrlCreateFromPath API:
//You get this path from Registry
LPCTSTR m_strBrowser = L"C:\\Program Files (x86)\\Internet Explorer\\iexplore.exe";
LPCTSTR addr2 = L"C:\\Users\\UserName\\AppData\\Local\\Temp\\Report_View.htm";
DWORD dwSz_buff_addr2 = INTERNET_MAX_URL_LENGTH;
TCHAR buff_addr2[INTERNET_MAX_URL_LENGTH];
if(SUCCEEDED(UrlCreateFromPath(addr2, buff_addr2, &dwSz_buff_addr2, NULL))
{
ShellExecute(hMain, NULL, m_strBrowser, buff_addr2, NULL, SW_SHOWNORMAL);
}
Also I'm not sure the parameter should be quoted in itself (it doesn't have space characters anyway), also not sure about the escaping.
Try:
LPCTSTR addr2 = L"file:///C|/Users/UserName/AppData/Local/Temp/Report_View.htm";

Can't send file from the appdata folder C++

So I was able to get the AppData folder via SHGetKnownFolderPath and converted the memory address it printed to a readable string via
SHGetKnownFolderPath(FOLDERID_RoamingAppData, NULL, NULL, &wszPath);
_bstr_t bstrPath(wszPath);
std::string strPath((char*)bstrPath);
newstring.append(strPath);
newstring.append(secondvar);
So you probably noticed the newstring.append. What I do is append the folder name I want and file to the end of the AppData location which is C:\Users\*Username*\AppData\Roaming(and append here my folder and file).
Then I use cURL to send the file from newstring to my cURL function called sendfile, however because of the hacks I tried to convert the memory address to a readable string and then append the other information, I then got a heap corrupted message.
I then tried manually putting the path to the directory and file to cURL function curl_formadd and it still wouldn't work. However, if there is a file where the application is, and use it for sending through HTTP, it works. If I add a full path, i.e C:\Users\*Username*\AppData\Roaming\myfolder\myfile.txt to the curl_formadd function, nothing happens.
So how do I go about fetching that file from the directory I want and sending it with cURL?