Reading encrypted text in program in c++ - visual-studio-2010

I need some help to decrypt my text file and make it able to read in my program..
What I have programmed so far is to read the encrypted file, create a new file, decrypt it and read the newly created file..
I need to decrypt the encrypted file without having to create a new file that reads the decrypted text..
Well, Let me show you my code:
P.S Most of the include is not needed and I already know that
Visual studio 2010 Windows Form Application CLR
#pragma once
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <conio.h>
#include <stdio.h>
#include <iomanip>
namespace EncryptandDecryptfiletest {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::IO;
using namespace std;
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
/*Decryption --- When program loads*/
char ch,mod;
char key = 97;
char name[100] = "Encrypted.txt";
char target[100] = "TTO.txt";
ifstream fin("Encrypted.txt", ios::binary); // Reading file
if(!fin) //open the encrypted file in a binary mode
{
MessageBox::Show("Encrypted.txt did not open"); //If file does not exist
} //or any kind of error
ofstream fout;
fout.open(target,ios::binary); //Opens outputfile
if(!fout)
{ //Show error if any error occurs in opening new file
MessageBox::Show("TTO.txt did not open");
}
while(fin.get(ch))
{ // opens the Encrypted file
if(ch==EOF)break;
mod = ch + key;
if (mod > 255 ) mod -= 255;
fout << mod; //Writes decrypted text to TTO.txt
}
fin.close(); //Close the encrypted file
fout.close(); // Close the decrypted file
}
private: System::Void comboBox1_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) {
label1->Text = comboBox1->Text;
pictureBox1->Load("Images\\" + comboBox1->SelectedItem->ToString() + ".png");
//String^ openFileTest = "Encrypted.txt"; // Opens the encrypted .txt file
String^ openFileTest = "TTO.txt"; //Opens the newly created file that is decrypted
try //Reading the .txt file
{
StreamReader^ DataIn = File::OpenText(openFileTest);
String^ DataStr;
int count = 0;
array<String^>^ result;
array<Char>^ separ = gcnew array<Char>{'"'}; //After each Quote gets a new value of result[x]
while((DataStr = DataIn->ReadLine()) != nullptr)
{
count++;
result = DataStr->Split(separ);
if(comboBox1->Text == result[0]) // result[0] = Name
{
textBox1->Text = result[1]; //reads first word in txt file
textBox2->Text = result[2]; //second word in txt file
textBox3->Text = result[3]; //third word in txt file
}
} // ends while()
} // ends try
catch (Exception^ e)
{
if(dynamic_cast<FileNotFoundException^>(e))
MessageBox::Show("File " + openFileTest + " not found");
}
} // Ends comboBox1_SelectedIndexChanged void
};
}
You have my decryption code and the code I want to use..
I have uploaded the code for you to use on your computer because it is fairly hard for me to explain..
I want to be able to read the encrypted file in my program, without having to writing a new file to decrypt it..
I hope anyone is able to help me
Decrypted & Encrypted .txt file Included (And images)
--> Program .rar pack link <--
Build it with Visual Studio 2010

Just replace the output file stream with a MemoryStream.
The first thing to do is decompose into functions. Since you read your streams byte per byte, you won't need readers, which is good.
void Decrypt(Stream^ input, Stream^ output)
{
char key=97;
int byteRead;
while((byteRead=input->ReadByte()) >= 0)
{
char ch = (char)byteRead;
char mod = (char)(ch+key)
output->WriteByte(mod);
}
}
//When loading
MemoryStream^ ms = gcnew MemoryStream();
{
FileStream^ fs = File::OpenRead(L"encrypted.txt");
Decrypt(fr, ms);
delete fs;
}
ms.Seek(0, SeekOrigin::Begin);
//Later, read from the memory stream

Related

How to feed Point Cloud from a file into a grid_map in ROS

I started working on a project that turns 3d point clouds from a file into grid_map. After successfully having set all my project in CMake I was trying to prepare a small example. I am already able to publish a grid_map from this tutorial as it is possible to see from the print screen below:
Also from this source it seems to be possible to feed a grid_map with some point clouds that I have in a file on my Desktop.
However I am finding this process a little bit difficult mostly because I am still not confident with grid_map as I started working with it recently.
Below I am putting the code I am using to try to feed grid_map with a point cloud file I have on my Desktop:
#include <ros/ros.h>
#include <grid_map_ros/grid_map_ros.hpp>
#include <Eigen/Eigen>
#include <grid_map_msgs/GridMap.h>
#include <string>
#include <cstring>
#include <cmath>
#include <iostream>
#include <sensor_msgs/PointCloud.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
using namespace grid_map;
class Point_CLoud_Reader
{
public:
Point_CLoud_Reader();
void pointCloudCallback(const sensor_msgs::PointCloudConstPtr& msgIn);
void readPCloud();
void writeToGridMap();
pcl::PointCloud<pcl::PointXYZ> cloud;
private:
ros::NodeHandle _node;
ros::Publisher pCloudPub;
ros::Subscriber pCloudSub;
std::string _pointTopic;
};
Point_CLoud_Reader::Point_CLoud_Reader()
{
_node.param<std::string>("pointcloud_topic", _pointTopic, "detections");
ROS_INFO("%s subscribing to topic %s ", ros::this_node::getName().c_str(), _pointTopic.c_str());
pCloudPub = _node.advertise<sensor_msgs::PointCloud>("/point_cloud", 100, &Point_CLoud_Reader::pointCloudCallback, this);
}
void Point_CLoud_Reader::pointCloudCallback(const sensor_msgs::PointCloudConstPtr &msgIn)
{
sensor_msgs::PointCloud msgPointCloud = *msgIn;
//msgPointCloud.points = cloud; // <-- Error Here
pCloudPub.publish(msgPointCloud);
}
void Point_CLoud_Reader::readPCloud()
{
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
if(pcl::io::loadPCDFile<pcl::PointXYZ> ("/home/to/Desktop/wigglesbank_20cm.pcd", *cloud) == -1) // load point cloud file
{
PCL_ERROR("Could not read the file /home/to/Desktop/wigglesbank_20cm.pcd \n");
return;
}
std::cout<<"Loaded"<<cloud->width * cloud->height
<<"data points from /home/to/Desktop/wigglesbank_20cm.pcd with the following fields: "
<<std::endl;
for(size_t i = 0; i < cloud->points.size(); ++i)
std::cout << " " << cloud->points[i].x
<< " " << cloud->points[i].y
<< " " << cloud->points[i].z << std::endl;
}
int main(int argc, char** argv)
{
// initialize node and publisher
ros::init(argc, argv, "grid_map_test");
ros::NodeHandle nh;
ros::Publisher pub = nh.advertise<grid_map_msgs::GridMap>("grid_map", 1, true);
ros::Publisher pCloudPub= nh.advertise<sensor_msgs::PointCloud>("point_cloud", 1, true);
pcl::PointCloud<pcl::PointXYZ> cloud;
// create grid map
GridMap map({"elevation"});
map.setFrameId("map");
map.setGeometry(Length(1.2, 2.0), 0.03);
ROS_INFO("Created map with size %f x %f m (%i x %i cells).",
map.getLength().x(), map.getLength().y(),
map.getSize()(0), map.getSize()(1));
// work with grid-map in a loop
ros::Rate rate(30.0);
while (nh.ok()) {
// add data to grid-map and point cloud from file just read
ros::Time time = ros::Time::now();
for(GridMapIterator it(map); !it.isPastEnd(); ++it)
for(int i = 0; i < cloud.points.size(); i++)
{
Point_CLoud_Reader readCloud;
readCloud.readPCloud(); // <-- Not reading point clouds
Position position;
map.getPosition(*it, position);
map.at("elevation", *it) = -0.04 + 0.2 * std::tan(3.0 * time.toSec() + 5.0 * position.y()) * position.x();
}
// publish a grid map and point cloud from file just read
map.setTimestamp(time.toNSec());
grid_map_msgs::GridMap msg;
sensor_msgs::PointCloud cloud;
GridMapRosConverter::toMessage(map, msg);
//GridMapRosConverter::toPointCloud(msg,cloud); <-- Error Here
pub.publish(msg);
pCloudPub.publish(cloud);
ROS_INFO_THROTTLE(1.0, "Grid map (timestamp %f) published.", msg.info.header.stamp.toSec());
// wait for next cycle
rate.sleep();
}
return 0;
}
Thanks for pointing in the right direction and shedding light on this issue

How to Search a file in QDir

I am developing an Application for MAC OS X. In which I have to find files in folder. Problem is that I want to give comfort, to user, to search a file by entering a QString. This QString may be the exact name of file or a text contain in the file name.Suppose the file name is "mysamplefile.txt". So if user enter either 'my' ; 'mysample' ; 'samplefile' ; 'mysamplefile' or 'mysamplefile.txt'. In all cases I want to get the QFileInfo for that file. I also give checkbox option 'Match Case' or 'Ignore case' to the user to get fileinfo. I have a QStringList for the strings that user want to search and I also have a QStringList of the locations selected by the user. So I want to search each string name(from QStringList strSearchFileName) in every Path(QStringList searchingdirectorylist). And I want to make a final QFileInfoList for all files after the searching process.
void MainWindowWipe::onSearchingProcess(QStringList strSearchFileName, QStringList searchingdirectorylist)
{
for(int i=0; i<strSearchFileName.size();i++)
{
for(j=0; j<searchingdirectorylist.size();j++)
{
QDir dir(searchingdirectorylist[j]);
dir.setNameFilters(QStringList(strSearchFileName[i]));
dir.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
QFileInfoList fileList = dir.entryInfoList();
for (int k=0; k<fileList.count(); k++)
{
QString temp = "";
temp = fileList[k].absoluteFilePath();
}
dir.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
QStringList dirList = dir.entryList();
QStringList newList;
for (int l=0; l<dirList.size(); ++l)
{
QString newPath = QString("%1/%2").arg(dir.absolutePath()).arg(dirList.at(i));
newList<<newPath;
onSearchingProcess(strSearchFileName,newList);
}
}
}
}
This function is not working for me this work only when if I search only one file with exact name. But I want to search multiple files with not exact name.
You need to iterate through all the files and folders using a recursive function (or use the iterator). On each iteration you can use the QString::contains() to find out if the file's name contains the target string. Save each matching file name in a list.
#include <QCoreApplication>
#include <QDebug>
#include <QDirIterator>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString targetStr = "init"; // What we search for
QFileInfoList hitList; // Container for matches
QString directory = "D:/python/"; // Where to search
QDirIterator it(directory, QDirIterator::Subdirectories);
// Iterate through the directory using the QDirIterator
while (it.hasNext()) {
QString filename = it.next();
QFileInfo file(filename);
if (file.isDir()) { // Check if it's a dir
continue;
}
// If the filename contains target string - put it in the hitlist
if (file.fileName().contains(targetStr, Qt::CaseInsensitive)) {
hitList.append(file);
}
}
foreach (QFileInfo hit, hitList) {
qDebug() << hit.absoluteFilePath();
}
return a.exec();
}

Usage of spoolFileName() of the Wt library

After I upload a file, I am trying to print out its spoolFileName() but although the application runs smoothly it seems as if the string of the name is empty. Any idea where it is wrong? (It's not the size of the file, it's less than 50k)
#include <Wt/WApplication>
#include <Wt/WFileUpload>
#include <Wt/WProgressBar>
#include <Wt/WBreak>
#include <Wt/WContainerWidget>
#include <Wt/WLineEdit>
#include <Wt/WPushButton>
#include <Wt/WText>
#include <Wt/Http/Request>
#include <Wt/WString>
using namespace Wt;
class HelloApplication: public WApplication {
public:
HelloApplication(const WEnvironment& env);
private:
WPushButton *uploadButton;
Wt::WFileUpload *fu;
Wt::WString g;
void greet();
void fileUploaded();
};
HelloApplication::HelloApplication(const WEnvironment& env) :
WApplication(env) {
root()->addStyleClass("container");
setTitle("Hello world"); // application title
fu = new Wt::WFileUpload(root());
fu->setFileTextSize(50); // Set the maximum file size to 50 kB.
fu->setProgressBar(new Wt::WProgressBar());
fu->setMargin(10, Wt::Right);
// Provide a button to start uploading.
uploadButton = new Wt::WPushButton("Send", root());
uploadButton->setMargin(10, Wt::Left | Wt::Right);
// Upload when the button is clicked.
uploadButton->clicked().connect(this, &HelloApplication::greet);
}
void HelloApplication::greet() {
fu->upload();
uploadButton->disable();
fu->uploaded().connect(this, &HelloApplication::fileUploaded);
g = fu->spoolFileName();
}
void HelloApplication::fileUploaded(){ // application title
root()->addWidget(new WText(g.value()));
}
WApplication *createApplication(const WEnvironment& env) {
return new HelloApplication(env);
}
int main(int argc, char **argv) {
return WRun(argc, argv, &createApplication);
}
I think the filename for the spool file is only known after the file is uploaded. Move
g = fu->spoolFileName();
to HelloApplication::fileUploaded().

What causes ambiguous symbol errors? C++

I am trying to learn C++ by doing a small windows phone app. Currently I am just following a tutorial to get to grips with developing for the windows phone. However, I have encountered a ambiguous signal error when trying to build the code. I am used to the niceties associated with Java and am a bit lost as to what could be causing this error. The error dump I get is:
1>c:\program files (x86)\windows phone kits\8.0\include\wrl\event.h(740): error C2872: 'EventRegistrationToken' : ambiguous symbol
1> could be 'c:\program files (x86)\windows phone kits\8.0\include\eventtoken.h(51) : EventRegistrationToken'
1> or 'c:\program files (x86)\windows phone kits\8.0\windows metadata\windows.winmd : Windows::Foundation::EventRegistrationToken'
1> c:\program files (x86)\windows phone kits\8.0\include\wrl\event.h(1035) : see reference to class template instantiation 'Microsoft::WRL::EventSource<TDelegateInterface>' being compiled
1>c:\program files (x86)\windows phone kits\8.0\include\wrl\event.h(814): error C2872: 'EventRegistrationToken' : ambiguous symbol
1> could be 'c:\program files (x86)\windows phone kits\8.0\include\eventtoken.h(51) : EventRegistrationToken'
1> or 'c:\program files (x86)\windows phone kits\8.0\windows metadata\windows.winmd : Windows::Foundation::EventRegistrationToken'
The code is attached below - sorry for giving the whole file, but I literally dont know where to start. Any help would be greatly appreciated.
Thanks
#include "pch.h"
#include "WindowsPhoneGame.h"
#include "BasicTimer.h"
//#include <string.h>
#include <sstream>
//using namespace std;
using namespace Windows::ApplicationModel;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::UI::Core;
using namespace Windows::System;
using namespace Windows::Foundation;
using namespace Windows::Graphics::Display;
using namespace concurrency;
WindowsPhoneGame::WindowsPhoneGame() :
m_windowClosed(false),
m_windowVisible(true)
{
}
void WindowsPhoneGame::Initialize(CoreApplicationView^ applicationView)
{
applicationView->Activated +=
ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &WindowsPhoneGame::OnActivated);
CoreApplication::Suspending +=
ref new EventHandler<SuspendingEventArgs^>(this, &WindowsPhoneGame::OnSuspending);
CoreApplication::Resuming +=
ref new EventHandler<Platform::Object^>(this, &WindowsPhoneGame::OnResuming);
m_renderer = ref new Renderer();
}
void WindowsPhoneGame::SetWindow(CoreWindow^ window)
{
window->VisibilityChanged +=
ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &WindowsPhoneGame::OnVisibilityChanged);
window->Closed +=
ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &WindowsPhoneGame::OnWindowClosed);
window->PointerPressed +=
ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &WindowsPhoneGame::OnPointerPressed);
window->PointerMoved +=
ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &WindowsPhoneGame::OnPointerMoved);
window->PointerReleased +=
ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &WindowsPhoneGame::OnPointerReleased);
m_renderer->Initialize(CoreWindow::GetForCurrentThread());
}
void WindowsPhoneGame::Load(Platform::String^ entryPoint)
{
}
void WindowsPhoneGame::Run()
{
BasicTimer^ timer = ref new BasicTimer();
while (!m_windowClosed)
{
if (m_windowVisible)
{
timer->Update();
CoreWindow::GetForCurrentThread()->Dispatcher- >ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
m_renderer->Update(timer->Total, timer->Delta);
m_renderer->Render();
m_renderer->Present(); // This call is synchronized to the display frame rate.
}
else
{
CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
}
}
}
void WindowsPhoneGame::Uninitialize()
{
}
void WindowsPhoneGame::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
{
m_windowVisible = args->Visible;
}
void WindowsPhoneGame::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
{
m_windowClosed = true;
}
void WindowsPhoneGame::OnPointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
{
ostringstream sstream;
sstream << "Pressed at: " << "X: " << args->CurrentPoint->Position.X << " Y: " << args->CurrentPoint->Position.Y << "\n";
string s = sstream.str();
OutputDebugStringA(s.c_str());
}
void WindowsPhoneGame::OnPointerMoved(CoreWindow^ sender, PointerEventArgs^ args)
{
ostringstream sstream;
sstream << "Moved at: " << "X: " << args->CurrentPoint->Position.X << " Y: " << args->CurrentPoint->Position.Y << "\n";
string s = sstream.str();
OutputDebugStringA(s.c_str());
}
void WindowsPhoneGame::OnPointerReleased(CoreWindow^ sender, PointerEventArgs^ args)
{
ostringstream sstream;
sstream << "Released at: " << "X: " << args->CurrentPoint->Position.X << " Y: " << args->CurrentPoint->Position.Y << "\n";
string s = sstream.str();
OutputDebugStringA(s.c_str());
}
void WindowsPhoneGame::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args)
{
CoreWindow::GetForCurrentThread()->Activate();
}
void WindowsPhoneGame::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
{
// Save app state asynchronously after requesting a deferral. Holding a deferral
// indicates that the application is busy performing suspending operations. Be
// aware that a deferral may not be held indefinitely. After about five seconds,
// the app will be forced to exit.
SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();
m_renderer->ReleaseResourcesForSuspending();
create_task([this, deferral]()
{
// Insert your code here.
deferral->Complete();
});
}
void WindowsPhoneGame::OnResuming(Platform::Object^ sender, Platform::Object^ args)
{
// Restore any data or state that was unloaded on suspend. By default, data
// and state are persisted when resuming from suspend. Note that this event
// does not occur if the app was previously terminated.
m_renderer->CreateWindowSizeDependentResources();
}
IFrameworkView^ Direct3DApplicationSource::CreateView()
{
return ref new WindowsPhoneGame();
}
[Platform::MTAThread]
int main(Platform::Array<Platform::String^>^)
{
auto direct3DApplicationSource = ref new Direct3DApplicationSource();
CoreApplication::Run(direct3DApplicationSource);
return 0;
}
You're using a lot of namespaces. It would appear that
EventRegistrationToken
Is defined in
Windows::Foundation; //windows.winmd
And again in eventtoken.h. Not sure which namespace this would apply to, could be global. Ditch the
using namespace Windows::Foundation;
and then you can access the respective implementations like this:
//eventtoken.h impl
EventRegistrationToken();
//the one in Foundation namespace:
Windows::Foundation::EventRegistrationToken();
Although it looks like you don't need this function, so it may not matter, this is just for example, and for how... since you need to remove this namespace, how you can now access the other members of this namespace.
I imagine you coud safely do this as well, though I don't necessarily recommend it:
using namespace Windows;
Foundation::EventRegistrationToken();
I had this same issue with just WP8 SDK projects.
Fix: Remove using Windows::Foundation from the .h file and use the full namespace for calling your object types.
Windows::Foundation::IAsyncOperation<String^> ^Blah();
instead of
IAsyncOperation<String^> ^CreateSampleData();

How to hand a file path (text box value) to a file reading function in c++?

I created a file chooser for windows it returns me a chosen file path. I want to read the given file but I do not know how to pass the file path to the right function.
File Form1.h I have a button action and inside of it I can get openFileDialog1->FileName but I do not know how to pass this variable to a readFile() function inside of main.cpp file.
I created a method to return the path:
System::String^ filePath;
....
private: System::String^ getPath() { return filePath; }
Here is the file-pickers code:
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
Stream^ myStream;
OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog;
openFileDialog1->InitialDirectory = "c:\\";
openFileDialog1->Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1->FilterIndex = 2;
openFileDialog1->RestoreDirectory = true;
if ( openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK ){
if ( (myStream = openFileDialog1->OpenFile()) != nullptr ){
// Insert code to read the stream here.
textBox1->Text = openFileDialog1->FileName; //text box displays the chosen path
myStream->Close();
}
}
}
The variable is set on button click:
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
filePath = textBox1->Text;
}
How to call the return methods in my main.cpp:
#include "stdafx.h"
#include "Form1.h"
using namespace main;
using namespace std;
[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
// Enabling Windows XP visual effects before any controls are created
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
// Create the main window and run it
Application::Run(gcnew Form1());
System::String^ p1 = /*Something missing her?*/getPath1(); //I am guessing it should look like this...
return 0;
}
Put the file name in a public property (public field, if it's what you prefer) in the Form1 class (or make your getPath() method public) then:
Form1^ form = gcnew Form1();
Application::Run(form);
String^ p1 = form->FileName;

Resources