How do i literally open a file using code in c++ - c++

I have written a code in which i want to open a HTM file when i select a particular option...
To achieve this i have created a batch file and opened it using system() as shown in code..
This is my code:
code:
#include <iostream.h>
#include <stdlib.h>
#include <dos.h>
#include <process.h>
void main()
{
cout<<"Hello World";
delay(3000);
system("a.bat");
delay(1000);
}
a.bat code:
start iexplore.exe c:\Turbo\TC\BIN\Hello.htm
When i just use this line in command line it executes but when i want to execute it using c++ code i get a bad filename or command error...
Please tell me if i am going wrong somewhere here.. or what can i do.
Please help..
Thank You..:)

Since most of your code isn't particularly portable anyway, the right way is almost certainly to use ShellExecute to "execute" the HTML file directly. I, for one, would have to be pretty desperate before I'd put up with a program using IE to open HTML files.
ShellExecute is Windows-specific, but your code isn't particularly portable right now. I suppose Unix (or similar) systems wouldn't actually stop you from naming a shell script whatever.bat, but it's certainly uncommon. You certainly shouldn't expect iexplore.exe to be available on most though (nor for executables in general to have a '.exe' extension).
ShellExecute(NULL, NULL, "c:\\Turbo\\TC\\BIN\\Hello.htm", NULL, NULL, SW_SHOWNORMAL);

You can use CreateProcess() API (http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425.aspx)

Related

Stopping an exe file from being run C++

I am creating an application to manage other applications or exe files on a user's computer, and stop them from accessing them at certain times (like ColdTurkey's application blocking feature).
The way I am trying to do this has not been working so far - I attempted to do this by opening the file dwShareMode set to 0 using the CreateFile function. This seems to work for files such as text files and does not allow the file to be opened, however this is not the case if I try and do this same approach on exe files, and the user is free to open the file.
I assume that exe files are not 'read' in the same way by Windows as a text file is read by notepad and that that means setting the dwShareMode to 0 does not affect it being opened, however I do not know what the difference between these are. Any help would be appreciated.
Code here (for the text file):
#include <windows.h>
#include <string>
#include <iostream>
using namespace std;
int main()
{
HANDLE test;
test = CreateFile("test.txt",
GENERIC_WRITE,
0,
NULL,
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,
NULL);
cout << "press enter to stop blocking application: ";
string b;
getline(cin, b);
cout << endl;
CloseHandle(test);
return 0;
}
Your code works fine for me to block execution of the file. You do need to specify OPEN_EXISTING instead of CREATE_NEW (because you're not trying to create a new file here).
Not a windows expert -- I'm used to Unix/Linux and use the Cygwin package so I can program "in Unix" on my Windows desktop -- but it looks to me like you need to set the lpSecurityAttributes parameter, the one that comes after dwShareMode.
I think the following page might be helpful:
https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx

C++ Open file seems to ruin file after run

Simply put, I double click on image1 in its file and it opens. I run the code bellow to open image1 and nothing comes up. So I go into the file with image1 again, double click on it, and windows photo viewer said, "Windows Photo Viewer can't display this picture because the file is empty." I did this with two other test images and the same thing is happening. Nothing important has been lost but this method seems to be erasing whichever file it tries to open and I'm very curious as to why and how I can fix it.
#include <iostream>
#include <fstream>
#include <chrono>
#include <thread>
void main()
{
std::ofstream imagetest;
imagetest.open("C:\\Users\\Filepath\\image1.jpg");
std::chrono::milliseconds dura(2000);
std::this_thread::sleep_for(dura);//Kept the sleep in because I didn't know if having the console up would affect the file/image from opening.
}
C++ is at lower level than scripts. open does not mean START.
You will have to execute a batch script with START C:\Users\Filepath\image1.jpg.
Or to learn many more libraries to do that in C++...
ofstream stands for “output file stream”. In addition to creating files that doesn’t exist, it also erases the contents of files that do exist. So you are opening an existing file for writing, and blowing away its contents in the process. You probably want ifstream, “input file stream”, for reading.
If you want to “open” the file in the sense of launching the default Windows application to read the file, you can use the Windows start command via system:
system("start \"C:\\Users\\Filepath\\image1.jpg\"");
Or the Windows ShellExecute API:
#include <windows.h>
ShellExecute(
NULL,
"open",
"C:\\Users\\Filepath\\image1.jpg",
NULL,
NULL,
SW_SHOWNORMAL
);
First,
std::ofstream imagetest;
is using the kernel to open the file for reading the file data..
this is probably what is corrupting the file from "opening" when you double click on it in windows
if you want to have windows open the image for viewing using the default application then you need a different method call because ofstream.open is not what you want.
try:
http://msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx
ShellExecute(NULL,"open","C:\\Users\\Filepath\\image1.jpg",NULL,NULL,SW_SHOW);
If you open a file stream for WRITE, then it will wipe all the content of that file, just like when you do that on a txt file. So you would always want to open the stream for read mode if you don't want that to happen

How to create a text file in a folder on the desktop

I have a problem in my project. There is a project folder on my desktop. I want to create a text file and write something include this text file. That is my code:
ofstream example("/Users/sample/Desktop/save.txt");
But I want to it could been run the other mac. I don't know what I should write addres for save.txt.
Can anyone help me?
Create a file and write some text to it is simple, here is a sample code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
std::ofstream o("/Users/sample/Desktop/save.txt");
o << "Hello, World\n" << std::endl;
return 0;
}
I hope that answers your question but I am not sure if i understand your question correctly, If not please add the details correctly of what you are trying to acheive.
[Update]:
Okay I guess the comment clears the problem.
Your real question is, You want to save the file in the desktop of the user who is playing the game. So getting the path of the current user's desktop is the problem.
I am not sure if there is an portable way to get desktop path but it can be done in following ways:
In Windows:
Using the SHGetSpecialFolderPath() function.
Sample code:
char saveLocation[MAX_PATH] = {0};
SHGetSpecialFolderPath(NULL, saveLocation, CSIDL_DESKTOPDIRECTORY, FALSE);
//Now saveLocation contains the path to the desktop
//Append your file name to it
strcat(saveLocation,"\\save.txt");
ofstream o(saveLocation);
In Linux:
By using environment variables $HOME
sample code:
string path(getenv("HOME"));
path += "/Desktop/save.txt";
ofstream o(path);
Rules defining where-you-should-save-file vary from platform to platform. One option would be to have it part of your compile script (that is you #define SAVEGAME_PATH as part of your compilation configuration), and thus your code itself remain more platform-agnostic.
The alternative is to find a save-data-management library that is already designed to be ported across different platforms. Whether it'd be a C or C++ or whatever-binary-interoperable library then no longer matters.
Just don't expect that to be part of C++ (the language).
if you want your program to run across platform,you'd better use the
relative path.
eg. "./output.txt",or better “GetSystemDirectory()”to obtain the system
directory to create a file,and then you could write or read the file
with the same path..

How to redirect printf output back into code?

i'm writing a little c++ app to wrap around the opencv haar training function (namely cvCreateTreeCascadeClassifier). The function throws a whole load of output to the console and I wish to parse this output so that I can populate various variables in my code.
The function I wish to use is not part of the actual openCV library; instead it has to be built with my code as part of the project. All of the output from the the function is via printf.
Question: Is it possible to intercept the printf statements before they end up on the console? I've managed to redirect them using freopen but this seems a little clumsy as I then need to parse the file and then delete it when the function call is finished. Also, the function is likely to be running for several hours (and possibly even weeks!) so the size of the file might be an issue if its constantly being appended too.
Requirements: I need this app to be c++ and to run on both windows and linux (but have no problem with conditional compile statements if need be). I would also like to be able to still see my cout and cerr messages on the console (just not the printf).
My googling has removed my will to live! Can anyone help with a solution via either code example or pointers to places I should be looking for an answer?
Thanks
What you can do is:
create a pipe
make the writable end of the pipe the new stdout
read from the readable part of the pipe
Reading and writing should happen in different threads or you risk that your program starves on one end of the pipe.
Here's a sample how to do the redirection in unix & windows:
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
/* gcc defined unix */
#ifdef unix
#include <unistd.h>
#endif
#ifdef WIN32
#include <io.h>
#define pipe(X) _pipe(X,4096,O_BINARY)
#define fileno _fileno
#define dup2 _dup2
#define read _read
#endif
#include <assert.h>
int main()
{
int fds[2];
int res;
char buf[256];
int so;
res=pipe(fds);
assert(res==0);
so=fileno(stdout);
// close stdout handle and make the writable part of fds the new stdout.
res=dup2(fds[1],so);
assert(res!=-1);
printf("Hi there\n");
fflush(stdout);
// reading should happen in a different thread
res=read(fds[0],buf,sizeof(buf)-1);
assert(res>=0 && res<sizeof(buf));
buf[res]=0;
fprintf(stderr,"buf=>%s\n",buf);
return 0;
}
This code should print
buf=>Hi there
(I'm using assert here, because I am too lazy to do real error checking for this example)
Encapsulate the lib into an application, and pipe the application's output to your application. Now write a script so that you don't have to run the apps together every time with a pipe.
Take a look at: http://www.unix.com/programming/136225-reading-stdout-pipe.html it seems promising, but i never tried it.

Launch IE from a C++ program

I have a program written in C++ which does some computer diagnostics. Before the program exits, I need it to launch Internet Explorer and navigate to a specific URL. How do I do that from C++?
Thanks.
Here you are... I am assuming that you're talking MSVC++ here...
// I do not recommend this... but will work for you
system("\"%ProgramFiles%\\Internet Explorer\\iexplore.exe\"");
// I would use this instead... give users what they want
#include <windows.h>
void main()
{
ShellExecute(NULL, "open", "http://stackoverflow.com/questions/982266/launch-ie-from-a-c-program", NULL, NULL, SW_SHOWNORMAL);
}
if you really need to launch internet explorer you should also look into using CoCreateInstance(CLSID_InternetExplorer, ...) and then navigating. depending on what else you want to do it might be a better option.
include <windows.h>
int main()
{
ShellExecute(0, "open",
"C:\\progra~1\\intern~1\\iexplore.exe",
"http://www.foo.com",
"",
SW_MAXIMIZE);
return 0;
}
Do you really need to launch IE or just some content in a browser? The ShellExecute function will launch whatever browser is configured to be the default. Call it like this:
ShellExecute(NULL, "open", szURL, NULL, NULL, SW_SHOW);
Using just standard C++, if iexplore is on the path then
#include <stdlib.h>
...
string foo ("iexplore.exe http://example.com");
system(foo.c_str());
If it's not on the path then you need to work out the path somehow and pass the whole thing to the system call.
string foo ("path\\to\\iexplore.exe http://example.com");
system(foo.c_str());
I'm with Glen and John, except I'd prefer to use CreateProcess instead. That way you have a process handle you can do something with. Examples might be Kill IE when you are done with it, or have a thread watching for IE to terminate (WaitForSingleObject with the process handle) so it could do something like restart it, or shut down your program too.
Try this
system("\"C:\Program Files\Internet Explorer\iexplore\" http://www.shail.com");
Works perfectly..