I need a background program C++ [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have created this program:
//Includes....
int main()
{
ifstream readfile("File.txt");
string str;
while(1)
{
getline(readfile,str);
system("cls");
Sleep(10000);
}
}
It's just a program that reads every 10 seconds a line from the file "File.txt"
I want to make it work on background,how can I do that?

If this was UNIX you would run the program from the shell with an ampersand "&" after the program name.

This sample hide console windows for you :
#include "windows.h"
#include fstream
#include string
#include stdio.h
using namespace std;
int main()
{
WCHAR path[260];
GetModuleFileName(NULL,path,260);
HWND console = FindWindow(L"ConsoleWindowClass",path);
if(IsWindow(console))
ShowWindow(console,SW_HIDE); // hides the window
//---------------------------------------------------
ifstream readfile("File.txt");
string str;
while(1)
{
getline(readfile,str);
system("cls");
Sleep(10000);
}
//----------------------------------------------------
if(IsWindow(console))
ShowWindow(console,SW_SHOW); // shows the window
}

Platform dependent. But I think you are using windows because of the "cls" command.
Why cant you just start a new command prompt and execute the correct .exe file. Then just minimize the program and do what you are supposed to do. If want to automate the startup phase (like cron in linux/unix) use the built in scheduler for windows.

If you want a (non-service) program that doesn't use a console window or any other windows at all, change main() to winmain(). Getting at command line arguments is a little more involved though.

I'm sorry, but I'm not sure I know what you mean... as far as I know (please correct me if I'm wrong) there is no way to run a simple C(++) program without a console window. However if you want it to "sleep" in a way that uses near no resources, then that can be achieved by checking current time and compering it with the time when you completed your last read.
Sleep function usually uses more resources than this, however it works just as well, so if resource cap isn't very very important then it will do just as well.
Hope this helped.

If you're launching your program from a Dos console, you can use the command start \B myprogram.exe, which is more or less equivalent to the unix ampersand. However, you'll need to keep the console open to keep the program running.
Another solution is to convert your application into a windows service, but then you'll have to rewrite (or wrap) your application.

If you want this because you're logging some kind of output and want to view the changes you could just use an editor such as TextPad which will automatically reload the file when it changes.
However you've not specified why you want this so this may not be appropriate in your case.

The proper way is to use a Windows service, there is enough information on Google on how to do this.

Related

c++ win32 open output file [duplicate]

This question already has answers here:
How can I call notepad.exe from a C program?
(3 answers)
Closed 5 years ago.
I just finished making software where given an input of a .jpg file, the program creates an output in .txt format.
Currently, the program creates the output and terminates, so the user has to manually find and open the output file. Is there a way that upon creation of the output file, that the program then opens it automatically?
By this I mean the program would open the output.txt file using notepad, just as if the user double clicked it himself. How would I go about doing this?
One can use the system () command. This invokes the system command processor.
You can give it the command that should be run in the cmd. This is not a efficient solution as system is not good for the efficiency and security of the program, if you are intending to use the code for some commercial build, using system is not recommended, for hobby programs you can surely use it.
Lets say that the file is picture.txt at location C:/file
Your code will be:
#include <iostream>
#include <cstdlib>
using namespace std;
int main ()
{
system ("notepad.exe c:/file/picture.txt");
return 0;
}

Alternative to system("PAUSE")? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I've recently read about how BAD system("PAUSE") is. I tried cin.get() but I don't know how to use it to pause a program. Other posts say to put a breakpoint after the statement. But I have no knowledge on how to do that. Any suggestions on how to pause my program? An example would be really appreciated.
Assuming that you are indeed working on Windows, the worst thing about system("PAUSE") is that it betrays a fundamental misunderstanding of your operating system's architecture. You do not need a code replacement for system("PAUSE"), because the code is the wrong place to solve the perceived problem.
Beginners like to put system("PAUSE") or even a portable alternative like std::cin.get() at the end of a program because otherwise "the window disappears" as soon as the program ends. Such logic, however, is deeply flawed. The window which you probably see while the program runs and which has made you ask this question is not part of the program itself but part of the environment in which the program runs.
A typical console program, however, must not assume details about the environment in which it is executed. You must instead learn to think in more abstract terms when it comes to input and output via std::cout and std::cin. Who says that your program is even visible for a human user? You may read from or write into a file; you may use pipes; you may send text to a network socket. You don't know.
#include <iostream>
int main()
{
std::cout << "Hello world\n"; // writes to screen, file, network socket...
}
Opening a graphical window and displaying text output on the screen is not in the scope of your program, yet using system("PAUSE") assumes exactly that one single use case and breaks all others.
If you use an IDE like Visual Studio and are annoyed by the fact that pressing F5 eventually results in the window disappearing before you have had the chance to see all output, here are three more sensible alternatives than manipulating the program itself:
Demystification. Observe that what Visual Studio really does is invoking the Visual C++ compiler behind the scenes in order to create an *.exe file. Open your own console window with cmd or with Tools > Visual Studio Command Prompt, locate the directory of that *.exe file and run it there (you should eventually also learn to start the compiler without Visual Studio's help, because that will give you a deeper understanding of the C++ build process).
Press CTRL+F5.
Place a breakpoint at the end of your code. Read the documentation if you don't know how.
I got one step closer, cin.ignore, but the user can only press enter if he/she wants to continue.
Example with cin.ignore():
#include <iostream>
int main()
{
cout << "Press enter to continue!\n";
cin.ignore();
//do something
return 0;
}
When you press enter it advances and does whatever you want it to do.

I need a function for C++ on a Mac like std::cin but with a timeout [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a Mac, so I don't have access to any windows.h functions, or any other windows libraries in C++. I am creating a game in C++. The controls of the game are the characters w,a,s,d. Currently I have the input method as std:cin. However, the problem is after the user types each character they must hit enter every time. Furthermore, the fact the std::cin does not timeout means that the user can essentially 'pause' the game to think about what move to make next (which ruins much of the fun of this game).
I need a function like std::cin but with a timeout of about .25 seconds. A function that will return as soon as the user types the character (without the need of the user hitting enter) would also work; but a function like std::cin with a timeout would be preferred. Please don't suggest window's library functions as I am again a Mac user using terminal.
Are there any standard c++ functions within the standard mac Libraries which will function equivalently to std::cin with a timeout of T that will run correctly in a Mac terminal?
Any reason you can't use int istream::get() ?
It's a blocking call though. I'm sure there is a better way to do it, but the quickest hack I can think of is to spawn a thread (just before calling get()) that waits for 0.25 secs and then writes some 'timeout char' say 't' to teh stream.
You can use the ncurses library, putting the terminal in cbreak() (non-blocking) mode, and disabling input delay with nodelay():
WINDOW *window = initscr();
cbreak();
nodelay(window, TRUE);
Then the getch() function will not block, returning ERR if no character is ready, so you can poll it in a loop and break when your timeout has been reached.
However, this may also require that you use ncurses for screen output, which may be a dealbreaker.

How to continue program after another window is opened [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
So I am an amateur programmer, currently enrolled in my second semester of C++ (yesterday we learned about structs just to give you an idea of what I know...).
I am creating a simple program to help me file documents at my internship.
I am using a system command(yes I know its dangerous and a big security risk), to open a pdf in firefox so that I can see the file and know where to put it.
I have successfully opened firefox and opened the pdf.
However my program stops running until I close firefox.
My question is how do I continue my program at the same time?
Is there an easier way to display a pdf in an executable?
edit:
Here is the function I use to open the firefox window with the pdf in it:
void openPDFBrowser (char array[])
{
ofstream outFile;
outFile.close();
outFile.open("PDF_browswer_handleScript.txt") ;
if(outFile.good())cout<<"OUTFILE GOOD" << endl;
outFile << "system("<<array<<")"<<endl;
system("PDF_browswer_handleScript.txt");
outFile.close();
}
the .txt file contails: firefox C:\Scans\Attorney.pdf
where firefox references a .bat file which contains the location of firefox.exe
I will take any suggestions
it just seemed easier to use an external browser to handle the display of the pdf file, although I'm still working out this threading idea
system is a blocking command - meaning it will stop your execution until that function returns. The only way to do this is to create a separate thread (or to fork a separate process, as noted by Chris Hayes), and to run the system (or CreateProcess, or exec) inside it, allowing main thread to continue.

How to plot graphs in Gnuplot in Real time in C++? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to plot a graph in real time using GNUplot and C++.
Does anyone know of any good libraries that does this?
Thanks
gnuplot supports input via pipes (on windows, there's a separate executable for this, pgnuplot). Then your program can send new commands to gnuplot, such as replot, just as if you were typing them into the gnuplot interface directly.
How you set up the pipe connection and write to the sending end of the pipe from your C++ program varies by operating system, so you'll have to tell us what you're using if you want more help.
On Windows, there's CreatePipe and then you set the hStdInput element of the STARTUPINFO struct you pass to CreateProcess. Ditto with hStdOutput if you need the status messages from pgnuplot.
On POSIX (Unix, Linux, Mac OSX, etc), you can just use popen as the quick way to get a unidirectional connection. For bidirectional, it works more like on Windows: pipe to get handles to the ends, then fork and in the child process call dup2 to associate stdin and stdout with the pipe, then exec to have gnuplot replace the child process, keeping the pipes you set up.
EDIT: From the gnuplot documentation:
The special filename ’-’ specifies
that the data are inline; i.e., they
follow the command. Only the data
follow the command; plot options like
filters, titles, and line styles
remain on the plot command line. This
is similar to << in unix shell script,
and $DECK in VMS DCL. The data are
entered as though they are being read
from a file, one data point per
record. The letter "e" at the start of
the first column terminates data
entry. The using option can be applied
to these data — using it to filter
them through a function might make
sense, but selecting columns probably
doesn’t!
Have you tried gnuplot interfaces in ANSI C?, this is an interface for C but in the same links there are some interface for C++. Or you could try PlPlot.
If you're interested in soft-realtime plotting, you're probably best of using a hardware accelerated graphics api (such as OpenGL), and plotting the chart yourself.
Look at http://search.cpan.org/~dkogan/feedGnuplot-1.08/bin/feedGnuplot This is a commandline utility, but also works well if controlled from a program.
In my C++ code, this worked (on mac OsX mavericks, using g++ Apple LLVM version 5.0):
#include <sys/types.h>
#include <unistd.h>
...
// ready to make a plot
pid_t childpid=fork();
if(childpid==0) {
// child process makes plot
std::FILE* pipehandle=popen("gnuplot -persist","w");
// make some plot. You can send multiple commands to the pipe each ending in \n
std::fprintf(pipehandle,"plot \"results.txt\" using 1:2 with lines\n");
std::fprintf(pipehandle,"quit\n");
std::fflush(pipehandle);
std::fclose(pipehandle);
// child process exits
exit(0);
}
// parent process waits for child process to exit
waitpid(childpid,NULL,0);
// you can now repeat to make other gnuplots; all will appear simultaneously in the
// terminal and are persistent after the parent process has finished.