Program that modifes string inside its exe - c++

I looking for example of program, that modifies a string inside its exe.
I work with C++, Visual Studio under Windows.
I searched working examples in Windows, but I can't find any working code.
I need simple code, that will ask user for string:
string strTest = "";
(if strTest != "")
{
cout << "Modified: " << strTest << endl;
}
cin >> strText;
And code should rewrite:
string strTest = "";
To string that typed user:
string strTest = "SomeStringFromUser";
How, in C++, do you modify a string (from string strTest = ""), to string, what a user typed? (for example to strTest = "foo")?

When an EXE is running on a Windows machine, the exe file is held open as a CreateFileMapping object with pages marked either as READONLY or COPY_ON_WRITE.
So when the exe writes to itself, the file is not modified. It just creates a new page backed by the swap file. But since the file is kept open, no-one else can open the EXE file and write to it either.
Other than hacking the page protection to turn off COPY_ON_WRITE - Which I'm not sure is even possible. The only way I can think to do this would be to write a little program that runs after your exe finishes and opens the .exe file and writes to it.
I've gotta believe that whatever you are trying to do, there is a better way to go about it.
--- Later ----
Ok, I get it now. you are looking to watermark your exe. Here's the thing, this is pretty easy to do in your installer before the exe starts. But once the .exe is running it's MUCH harder to do.
Here's what I would do.
declare a global string variable of the necessary size, say const char g_szWatermark[100] = "";
Build my exe, then look in the map file to find the address of the variable within its segment (remember about C++ name decoration)
parse the EXE header to find the where the segment begins in the exe.
add these two numbers to get the location of the string within the exe file, give this number to my installer
have the installer run a little program that asks the user for information and then writes it into the .exe. Note: you have do do this before the exe runs or it won't work!

A licensing scheme based on some open, established cryptographic mechanism is going to be your most robust solution. Something using standard PKI should be much simpler and more secure than attempting to implement self-modifying code.
To be honest though, there are a lot of companies that spend a lot of money on R&D creating copy protection and those systems are cracked within days of release. So if you're trying to thwart crackers then you have a long, hard road ahead.
If you just want to keep the honest people honest, a simple online activation using a GUID as the "license key" would be quite effective.

How about this:
#include <string>
#include <iostream>
int main()
{
std::string strTest = "";
std::getline(std::cin,strTest);
if (strTest != "")
{
std::cout << "Modified String: " << strTest << "\n";
}
else
{
std::cout << "Not modified\n";
}
}

Related

mkdir() isnt working with absolute filepath

I am using a raspberry pi to store data collected from a rocket launch. I am trying to create a directory which has the date and time built in, to hold multiple text and .csv files which hold interesting data. My code looks like:
string date = getDateTime(); //Returns a string like "Launch_2017_04_28_23:31:03"
string dated_directory = "~/Launch_System_Cpp/Source_Code/Launch_Data/" + date;
cout << dated_directory << endl;
if (mkdir(dated_directory.c_str(), ACCESSPERMS )) {
cout << "ERROR creating dated directory" << endl;
}
The executable itself is located in ~/Launch_Code_Cpp/.
I have been able to get this working with relative references, but I want this code to work no matter the directory it was run from. I haven't been able to get it working with absolute references; it always enters the if statement, and the directory doesn't exist when the program exits.
Can you tell me what I may be doing wrong when I try to make this directory? Is there a better way to make this directory?
The ~ character is converted to the home directory by the shell. Since you're not using a shell, you need to expand that yourself.

How to make a C++ program that works with a .txt file without showing it

My program needs to use a hidden text file to keep track of user's name.
But when the program starts, if it can't find the 'Name.txt' file in the same directory, it generates one that is visible to the user.
The user can view it, edit it, and so on. How can I prevent this from happening, so that only my program can modify the file?
Also, is there a better way to keep knowledge of the name of the user (keep in mind I'm new to programming in general, not only to C++)?
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
#include <Windows.h>
using std::string;
using std::cout;
using std::cin;
using std::ifstream;
using std::ofstream;
int main()
{
string line;
ifstream example;
example.open("Name.txt");
getline(example, line);
if (line.compare("") == 0)
{
example.close();
string con;
cout << "Welcome to this program!\n";
cout << "Do you want to register? (y/n) ";
cin >> con;
con[0] = tolower(con[0]);
if (con.compare("n") != 0)
{
string name;
ofstream one;
one.open("Name.txt");
cout << "What's your name? ";
cin >> name;
one << name;
one.close();
cout << "See you later " << name << ".";
Sleep(4000);
}
}
else
{
cout << "Welcome back " << line << ".";
example.close();
Sleep(4000);
}
}
EDIT : I just realised I said 'to keep track of the user'. Now I realized why you guys thought I wanted to do something bad with this program. I corrected it now, what I meant was 'to keep track of the user’s name'.
I understand that you want to maintain a file that contains the names of all the registered users, or some other kind of current-user-independent data.
The problem
Your code tries to open the file in the current working directory of the program. Unfortunately, it depends on the way the user has launched your program.
It also ignores possible errors during the opening when reading the file. So if the file isn't there, your code will open the file as ofstream for writing (which will create the file if it doesn't exist).
How to solve it ?
To fulfill your requirements, you should open the file in a predetermined location (for example fixed during the installation process, or in the program's configuration). See this article, on where to ideally store data and configuration files on windows platform.
If you want to make sure that the program only opens the file if it already exists, you should verify the result of the open on the ifstream and issue an error message if this failed:
example.open("Name.txt");
if (!example) {
cout << "OUCH ! Fatal error: the registration file couldn't be opened !" <<endl;
exit (1);
}
How to protect the file against users ?
Note however that if your program reads and writes data from the file, the user could find it also and edit it manually. This will be difficult to prevent.
Alternatively you could consider using the windows registry, which is less trivial for the user to edit (although not impossible). The major inconvenience of this approach is that it's system dependent and it will make the porting of your code to other platforms much more difficult.
If you want to fully protect your file, you could as suggested by Chris in the comment, encrypt the file. Encryption is complex business; Consider using a library such as openssl or a proven algorithm.
This will protect you against ordinary users. But you'd still be exposed to hackers able to reverse engineer your code and to find the encryption key that must be somehow embedded in your code to decrypt the file.

Writing to a .csv file with C++?

TL;DR I am trying to take a stream of data and make it write to a .csv file. Everything is worked out except the writing part, which I think is simply due to me not referencing the .csv file correctly. But I'm a newbie to this stuff, and can't figure out how to correctly reference it, so I need help.
Hello, and a big thank you in advance to anyone that can help me out with this! Some advance info, my IDE is Xcode, using C++, and I'm using the Myo armband from Thalmic Labs as a device to collect data. There is a program (link for those interested enough to look at it) that is supposed to stream the EMG, accelerometer, gyroscope, and orientation values into a .csv file. I am so close to getting the app to work, but my lack of programming experience has finally caught up to me, and I am stuck on something rather simple. I know that the app can stream the data, as I have been able to make it print the EMG values in the debugging area. I can also get the app to open a .csv file, using this code:
const char *path= "/Users/username/folder/filename";
std::ofstream file(path);
std::string data("data to write to file");
file << data;
But no data ends up being streamed/printed into that file after I end the program. The only thing that I can think might be causing this is that the print function is not correctly referencing this file pathway. I would assume that to be a straightforward thing, but like I said, I am inexperienced, and do not know exactly how to address this. I am not sure what other information is necessary, so I'll just provide everything that I imagine might be helpful.
This is the function structure that is supposed to open the files: (Note: The app is intended to open the file in the same directory as itself)
void openFiles() {
time_t timestamp = std::time(0);
// Open file for EMG log
if (emgFile.is_open())
{
emgFile.close();
}
std::ostringstream emgFileString;
emgFileString << "emg-" << timestamp << ".csv";
emgFile.open(emgFileString.str(), std::ios::out);
emgFile << "timestamp,emg1,emg2,emg3,emg4,emg5,emg6,emg7,emg8" << std::endl;
This is the helper to print accelerometer and gyroscope data (There doesn't appear to be anything like this to print EMG data, but I know it does, so... Watevs):
void printVector(std::ofstream &path, uint64_t timestamp, const myo::Vector3< float > &vector)
{
path << timestamp
<< ',' << vector.x()
<< ',' << vector.y()
<< ',' << vector.z()
<< std::endl;
}
And this is the function structure that utilizes the helper:
void onAccelerometerData(myo::Myo *myo, uint64_t timestamp, const myo::Vector3< float > &accel)
{
printVector(accelerometerFile, timestamp, accel);
}
I spoke with a staff member at Thalmic Labs (the guy who made the app actually) and he said it sounded like, unless the app was just totally broken, I was potentially just having problems with the permissions on my computer. There are multiple users on this computer, so that may very well be the case, though I certainly hope not, and I'd still like to try and figure it out one more time before throwing in the towel. Again, thanks to anyone who can be of assistance! :)
My imagination is failing me. Have you tried writing to or reading from ostringstream or istringstream objects? That might be informative. Here's a line that's correct:
std::ofstream outputFile( strOutputFilename.c_str(), std::ios::app );
Note that C++ doesn't have any native support for streaming .csv code, though, you may have to do those conversions yourself. :( Things may work better if you replace the "/"'s by (doubled) "//" 's ...

Reading input from .exe and writing to a .exe for reading Chess engine commands

I am searching all day for an example c++ program which will use ready .exe file which has as an output strings and then waits for standart input and again prints outputs and so on and so forth.
For example my c++ program will use standard output to write "uci" to a .exe program, the .exe program will reply with a string again which I will be able to read in my c++ program and again I will send a new string and will wait for a reply by the .exe.
I found something about pipes but I thought they were really difficult to understand.Is there any ready library/interface I could use? Or any example you can give me with pipes?
If you just know basics of c++ may be you should follow this as it does not require any external libs, though some say system is evil, its okay if it doesn't go to production level programs
int main()
{
std::string in;
while(std::cin >> in)
{
std::string cmd = std::string("/full/path/to/second.exe <") + in + " >outfile.txt";
system(cmd.c_str());
std::ifstream fin("outfile.txt");
std::cout << fin;
}
}
If you open to use bigger frameworks, there is an easy to use class in Qt to handle processes: http://doc.qt.io/qt-5/qprocess.html.
QProcess exe;
exe.start("foo.exe");
exe.write("uci");
exe.waitForReadyRead();
auto result = exe.readAll();
On windows you can use CreateProcess/CreatePipe, but the code will be a lot more verbose. Example:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx

What would cause ifstream code to fail on OS X?

I have the following code
string fileName = "assets/maps/main.json";
std::ifstream file(fileName);
std::string temp;
if(!file.good())
{
LOG(logERROR) << "Failed to open map file: " << fileName;
//return;
}
LOG(logDEBUG) << "file Char Count: " << file.gcount();
while(std::getline(file, temp))
{
mapString += temp;
}
file.close();
This code works superbly on Windows 8. When I take this program over to OS X, the file fails to open 100% of the time. Or to be more concise, file.good() never returns true. I intentionally commented out the return there to help debugging for later code.
Anyway, this has driven me insane. I cannot figure out why it's failing on OS X. I've tried different directories, re-created the file on OS X to make sure it wasn't an encoding or line-end issue, nothing at all.
What else can I do to debug, or what might I try as an alternative?
I've also checked the file permissions themselves and they are all fine. I have many other types of files in the same directory structure (images, music, fonts) and they all open fine, it's just this JSON file that fails, and any new derivatives of this file also fail.
When you start a program on Linux or MacOSX, the working directory will be wherever the user is. So, if your game needs to find files, you need to make use of the appropriate preference system. Mac has a concept of a 'bundle' that allows a program to come with data files and use find them, you'll have to learn how to make one. You can look inside all the '.app' directories in your /Applications directories for many examples.