program not working after being opened using ShellExecute - c++

EDIT :
Turns out that the problem is that in iosfwd, it throws the exception at line 506 :
Exception thrown: write access violation.
_Left was 0xCCCCCCCC.
To answer :How to Fix: Exception thrown: write access violation. _Left was 0xCCCCCCCC
I am making a program where it launches another program in its same directory that updates a text file using ShellExecute.
The program begins by taking a string using getline and then uses ShellExecute to launch another program that uses fstream to update a file.
Here is the relevant part of the program:
cout << "Please enter Program Name:" << endl;
getline(cin.ignore(), a);
system("cls");
os.open("tempstring.txt");
os << a;
os.close();
LPCSTR filename = "NewProgScript.exe";
LPCSTR Location = NULL;
ShellExecute(NULL, "open", filename, NULL, Location, SW_SHOWNORMAL);
/*>> >> >> >> >> rest is irrelevant << << << << << <<*/
bool end = false;
do
{
system("cls");
is.open("tempdone.txt");
is >> x;
is.close();
if (x == 1) { end = true; }
if (x == 2) { os.open("tempdone.txt"); os << 0; os.close(); Errors Err; Err.Error(41); }
cout << "Please wait while Files Update." << endl;
Sleep(1000);
} while (end == false);
"NewProgScript.exe" is launched here.
NewProgScript.exe code:
#include "pch.h"
#include <fstream>
#include <string>
#include <Windows.h>
#include <iostream>
using namespace std;
int main()
{
ofstream os;
ifstream is;
string a, nouse;
string Progs[20];
is.open("tempstring.txt");
getline(is, nouse);
is.close();
cout << "UPDATING DATABASE.. DO NOT EXIT!" << endl;
string name, ending, end;
ending = ".txt";
name = "Prog";
for (int count = 1; count < 20 + 1; count++)
{
end = name + to_string(count) + ending;
is.open(end);
getline(is, Progs[count]);
is.close();
}
for (int count = 1; count < 20 + 1; count++)
{
end = name + to_string(count) + ending;
if (Progs[count] == "NULL")
{
os.open("end");
os << nouse;
os.close();
os.open("tempdone.txt");
os << 1;
os.close();
Sleep(500);
exit(EXIT_SUCCESS);
}
}
os.open("tempdone.txt");
os << 2;
os.close();
}
The problem is that when this is launcher early on using ShellExecute, it does not update the file "tempdone.txt"
It does however work when I manually click open it externaly.
How can i fix this?
P.S: sorry for the Very long post! Also I am sorry of i make dumb or naive mistakes, i am not very good yet :/

Related

Trying to make something write to a file in c++

I tried programming a file writer, but when i try to write to a file with something that has multiple words it will suddenly create files.
My code
#include <fstream>
#include <iostream>
#include <unistd.h>
int main(int argc, char *argv[]) {
char cwd[256];
while (true) {
getcwd(cwd, 256);
std::string cwd_s = (std::string)cwd;
std::string Input;
std::cout << cwd_s << "> ";
std::cin >> Input;
std::ofstream file(Input);
std::cout << "cmd /";
std::cin >> Input;
file << Input;
};
for (int i; i < argc; i++) {
std::cout << argv[i] << '\n';
};
return 0;
}
I expected to get this:
C:\Users\code> File.txt
cmd /hello world!
File.txt
hello world!
But it only had "hello", it created another file named world!
I have tried changing the code, but to no avail.
So I have wrote this code that I think does what you expect. The behavior you were seing is because you used the same string to store the filename and the user input. Also you redefined a new file every loop (without closing the previous one). I added a signal handler since if you press Ctrl+C the program would quit without saving/closing the file.
I added comments about how you can make a better CLI interface (if you're interested)
#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>
std::ofstream outfile;
void signalHandler(int signum) {
outfile.close();
exit(signum);
}
int main() {
char cwd[256];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
std::cout << cwd << "> ";
} else {
std::cerr << "Error: Could not get current working directory." << std::endl;
return 1;
}
std::string filename;
std::getline(std::cin, filename);
outfile.open(filename);
// We intercept the Ctrl+C signal to close the file before exiting. Else nothing will be written to it.
// You can also use Ctrl+D (EOF: End Of File) to exit the program.
// The best praticte would be to implement a command line interface with a "quit" command. (like a map<string, function> for example)
signal(SIGINT, signalHandler);
// Another good practice is to check if the file did open correctly.
if (!outfile.is_open()) {
std::cerr << "Error: Could not open file for writing." << std::endl;
return 1;
}
std::cout << "cmd / ";
char ch;
while (std::cin.get(ch)) {
outfile.put(ch);
if (ch == '\n') {
std::cout << "cmd / ";
}
}
outfile.close();
return 0;
}
Hope it will help you ! And if you have any question about the code feel free to ask I'll explain !

Segmentation fault: unable to fix the problem

I'm new to C++, and I'm trying to write a project that interacts through command line. Right now, whenever I run my main (which is the executable), I always receive a segmentation fault error when the main program finished.
Edit comment:
I'm told by tutor to use as little as C++ features such as vectors or strings ... I'm also very new to C++, so i'm trying to utilize as many basic C functions as I can.
I'm
My main function looks like this:
int main(int argc, char** argv) {
cout << "starting mvote..." << endl;
int run_flag = 1;
char* actionBuffer = (char*)malloc(100 * sizeof(char));
char* action = (char*)malloc(16 * sizeof(char));
char* readPtr;
char exit[4] = { 'e','x','i','t' };
//parse command line argumentand get the filename
char* filename = argv[2];
cout << filename;
FILE* fp;
char line[64];
//from here, I'm opening the file and read it by lines
fp = fopen(filename, "r");
if (fp == NULL) {
cout << "file not exists";
return -1;
}
while (fgets(line, 64, fp) != NULL) {
cout << line << "\n";
}
fclose(fp);
while (run_flag == 1) {
cout << "what do you want?\n " << endl;
cin.getline(actionBuffer, 1024);
if (strcmp(actionBuffer, exit) == 0) {
cout << "bye!";
run_flag = 0;
break;
}
//if not exit, Look for the space in the input
readPtr = strchr(actionBuffer, ' ');
int size = readPtr - actionBuffer;
//extract the operation
strncpy(action, actionBuffer, size);
for (int i = 0; i < size; i++) {
cout << "operation:" << action[i];
}
// depend on the operation specified before the first empty space
run_flag = 0;
}
free(actionBuffer);
free(action);
return 0;
}
Description:
I first try to open up a csv file which lies in the same folder as main, and I read the file line by line. Then, I just implement a simple command where you can type exit and quit the program.
I allocate two memory, actionBuffer and action, which are used to hold command
Problem: a segmentation fault [core dumped] always exists when I type exit and hit enter, and then the process finished.
Research: So I learned that segmentation fault is due to accessing a memory that does not belongs to me. But where in my program am I trying to access such a memory?
Any advice is appreciated! Thank you.
Just to give you an idea, this would be an example of C++ code
#include<iostream>
#include<fstream>
#include<string_view>
#include<string>
#include<sstream>
#include<exception>
int main(int argc, char** argv) {
std::cout << "starting mvote...\n";
//parse command line argumentand get the filename
std::string filename = argv[2]; // NO CHECKS!
std::cout << filename <<'\n';
//from here, I'm opening the file and read it by lines
{
std::ifstream ifs(filename);
if (!ifs) {
throw std::invalid_argument("file not exists");
}
std::string line;
while (std::getline(ifs, line)) {
std::cout << line << '\n';
}
}
bool run_flag = true;
while (run_flag) {
std::cout << "what do you want?\n";
std::string userInput;
std::getline(std::cin, userInput);
if (userInput == "exit") {
std::cout << "bye!\n";
return 0;
}
std::stringstream userInputSs(userInput);
std::string operation;
while(userInputSs >> operation){
std::cout << "operation: " << operation << '\n';
}
}
}

failbit getting set with ifstream object, what can be the cause?

I have written a small C++ program to set a property in a text file. The implementation is as following:
#include <cstdio>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
const string PROPFILE = "./propfile";
const string TEMPFILE = PROPFILE + ".tmp";
int setProp(const string &key, const string &val) {
try {
ifstream original(PROPFILE, ios::in);
ofstream tempfile(TEMPFILE, ios::out | ios::trunc);
for (string line; getline(original, line); ) {
if (line.compare(0, key.size(), key) == 0 && line[key.size()] == '=') {
tempfile << key << '=' << val << endl;
} else {
tempfile << line << endl;
}
}
cout << "original.rdstate()" << original.rdstate() << endl;
original.close();
tempfile.close();
} catch (ifstream::failure e) {
cerr << e.what() << endl;
}
if (rename(TEMPFILE.c_str(), PROPFILE.c_str()) != 0) {
cout << "Could not move " + TEMPFILE << "to " << PROPFILE << endl;
return 1;
}
return 0;
}
int main(int argc, const char *argv[]) {
try {
return setProp(argv[1], argv[2]);
} catch (logic_error) {
cout << "Invalid args" << endl;
return 1;
}
}
However, when I try to compile and execute it from commandline via ./a.out TESTPROP TESTVALUE, the value IS set as expected in propfile but rdstate() returns 6 (which means failbit and eofbit are set), I can't understand why are they getting set, can somebody explain ?
Contents of propfile before running ./a.out TESTPROP TESTVALUE are:
TESTPROP=NOTHING
After running the progam:
TESTPROP=TESTVALUE
I'm just a student, please don't mind if it's a dumb question :)
This is expected behaviour, the failbit is set whenever there is a failure to read the expected value. Even if that failure is because of end of file.
For instance see here
If no characters were extracted for whatever reason (not even the
discarded delimiter), getline sets failbit and returns.

Memory access violation error c++

I'm trying to exchange messages using multiple covert channels.
So, basically, first i need to select the channel that i want to use for communication and then select the "destination_ip" of the user that i want to chat with and after that the
processMessage()
is called. Now, to move from one channel to another I have to close the existing connection and then open a new connection with the new channel that i want to use. My code below is modified to keep using the same channel after closing the connection and contain only the things that you need.
#include <channelmanager.hpp>
#include <thread>
#include <iostream>
#include <boost/test/unit_test.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <stdio.h>
#include <string.h>
#include <fstream>
#include <openssl/hmac.h>
struct CommunicationFixture {
CommunicationFixture() {
channelmanager.setErrorStream(&cout);
channelmanager.setOutputStream(&cout);
destination_ip = "";
channel_id = channelmanager.getChannelIDs()[0];
}
library::ChannelManager channelmanager;
vector<string> last_adapters;
string destination_ip;
string channel_id = "";
int processMessage(string message) {
if (message.compare("exit") == 0) {
channelmanager.closeConnection(destination_ip);
return 1;
}
vector<string> arguments;
boost::split(arguments, message, boost::is_any_of(" "), boost::token_compress_on);
if (arguments[0].compare("argument") == 0) {
if (arguments.size() < 2) {
cout << "Not enough arguments" << endl;
return 0;
}
string argument_list = arguments[1];
for (unsigned int i = 2; i < arguments.size(); i++) {
argument_list += " " + arguments[i];
}
channelmanager.setChannelArguments(destination_ip, argument_list);
cout << "Set channel argument to '" << argument_list << "'." << endl;
return 0;
}
if (message.compare("help") == 0) {
cout << "Help not available in chat mode. Close chat first with 'exit'" << endl;
return 0;
}
channelmanager.openConnection(destination_ip, channel_id);
channelmanager.sendMessage(destination_ip, message);
return 0;
}
int close(string destination){
cout << "closing.." << endl;
channelmanager.closeConnection(destination); //I believe i have the error because of this!
return 0;
}
};
BOOST_FIXTURE_TEST_SUITE(communication, CommunicationFixture)
BOOST_AUTO_TEST_CASE(basic_communication) {
selectAdapterId(0);
cout << "Test" << endl << endl;
printCommands();
cout << "Enter your command:" << endl;
string command;
int code = 0;
while (code != 2) {
std::getline(cin, command);
code = processCommand(command);
if (code == 1) {
// chat
cout << "chat started.." << endl;
int chatCode = 0;
while (chatCode != 1) {
std::getline(cin, message);
close(destination_ip);
chatCode = processMessage(message);
channelmanager.setErrorStream(&cout);
}
cout << "chat ended." << endl;
}
}
}
BOOST_AUTO_TEST_SUITE_END()
Note that, i think that the error happens due to the
function close()
because without it i don't get any errors. and the error doesn't happen immediately but after exchanging some messages. Here's the error:
unknown location(0): fatal error: in
"communication/basic_communication": memory access violation at
address: 0x00000024: no mapping at fault address
communicationTest.cpp(325): last checkpoint: "basic_communication"
test entry
Memory access violation happen when you are trying to access to an unitialized variable, in this case the channelmanager.
I can only see that you initialize channelmanager in the processMessage() method and you are closing the connection before initializing the channelmanager as it happen in:
close(destination_ip);
chatCode = processMessage(message);
Either you change the initialization or do not close it before the processMessage() method.
Memory access violation is also called a segmentation fault (or segfault), occurs when the program tries to access a memory location that doesn't exist, or is otherwise inaccessible. We call this trying to access an illegal memory location. That memory is either non-existent or we aren't aren't allowed to touch it.
If the first input from user is 'exit', which is going to call
if (message.compare("exit") == 0) {
channelmanager.closeConnection(destination_ip);
return 1;
}
In this case, destination_ip isn't initialised.

When compiling code antivirus says it's virus and delete it

Hi i try to make code in c++. This code only makes text file easy encrypted and save into a new file. And when i compile this code antivirus says, it is virus/spyware Gen:Variant.Kazy.20825. I dont know why it is virus.
Here is my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void controlParameters(int argc){ //check if input parameters are ok
if(argc == 1){
cout << "Pokud chcete text zasifrovat, spustte program s parametrem: -enc \"Nazev_souboru.txt\"\n";
cout << "Pokud ho chcete desifrovat, spustte program s parametrem: -dec \"Nazev_souboru.txt\"\n";
}else if(argc > 3){
cout << "Moc parametru. Spustte si program bez parametru.\n";
}else if(argc < 3){
cout << "Chybi jeden parametr. Spustte si program bez parametru.\n";
}else{
cout << "Vsechno vypada zatim dobre\n";
}
}
void encryption(string &file); //encrypt text file
void decryption(string &file); //decrypt text file
bool controlFile(string &file); //check if file can be opened
int main(int argc, char **argv){
controlParameters(argc);
string file;
file = argv[2];
if(controlFile(file)){
}else{
cout << "Soubor nesel nacist." << endl;
return -1;
}
cout << "Ukonceno.\nZmacknete ENTER pro pokracovani..."<<endl;
cin.get();
return 0;
}
bool controlFile(string &file){
ifstream ifs;
ifs.open(file);
if(ifs.is_open()){
ifs.close();
return true;
}else{
ifs.close();
return false;
}
}
void encryption(string &file){
ifstream ifs;
ofstream ofs;
string line;
ifs.open(file);
ofs.open("encrypt.txt");
if(ifs.is_open()){
while(!ifs.eof()){
getline(ifs,line);
int a = line.length();
int i = 0;
while(i < a){
ofs << ((char)(line[i]^100));
}
line.clear();
ofs << "\n";
}
}else{
cout << "Nelze nacist soubor" << endl;
}
}
void decryption(string &file){
ifstream ifs;
ofstream ofs;
string line;
ifs.open(file);
ofs.open("decrypt.txt");
if(ifs.is_open()){
while(!ifs.eof()){
getline(ifs,line);
int a =line.length();
int i = 0;
while(i < a){
ofs << ((char)(line[i]^100));
}
line.clear();
ofs << "\n";
}
}else{
cout << "Nelze nacist soubor" << endl;
}
}
It's good practice to exclude your source-control directories from virus scanners; they can cause performance and locking problems even if there are no false positives while performing source-control actions or compiling (I've seen it happen several times).
So if only to make your programming experience more reliable, disable the virus scanner on those directories.
You may still want to scan the final, released version of your executable to help avoid false positives: after all, even if it's not your fault the virus scanner chokes, it's not a good impression to leave behind on a user.
Antivirus software uses "heuristics" to determine what is a virus and what isn't. So it looks for patterns in the file that does things that it finds suspicious. I can't see anything directly wrong in your code, so I suspect it's a "false-positive". I personally don't like antivirus software, it causes more problems than it solves...
By the way, you could add the "output filename" to your encrypt/decrypt function, and make them one function! ;)