Keeping Console Window Open in Visual Studio (C) - visual-studio

I usually use XCode but was having a problem opening a file with this code:
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
int main(void )
{
printf("Hello");
FILE *filePtr;
filePtr = fopen( "test.txt", "r" );
if (filePtr == NULL)
{
fprintf(stderr, "Can't open \"test\"\n");
exit(EXIT_FAILURE);
}
else
{
int x;
printf("File open successful\n");
/* read one character at a time until EOF is reached */
while ((x = fgetc(filePtr)) != EOF)
{
//printf("%c", x);
fprintf(stderr, "%x\n",x);
}
}
fclose(filePtr);
system("pause");
return EXIT_FAILURE;
}
The console window closes so fast and at the bottom bar of VS it says: "'C_test.exe': Loaded 'C:\WINDOWS\WinSxS\x86_Microsoft.VC90.DebugCRT_1fc8b3b9a1e18e3b_9.0.30729.1_x-ww_f863c71f\msvcr90d.dll'
The program '[1116] C_test.exe: Native' has exited with code 1 (0x1)."
What does that mean?
Also, can anyone point me to good VS starting points / tutorials?

See also How to keep the console window open in Visual C++?

The reason you can't see it is because there is no possibility for your program to pause during execution. In Visual Studio the typical behavior is to close the console window the second the program has completed its execution.
The bottom bar is telling you that the program complete and what the return value was (1 in this case).
What I would also do is add code right before the exit point of the program with #ifdefs:
#ifdef VS_DEBUG
fgetc(STDIN);
#endif
Now your program will pause when it's done and wait for a keypress then close the window.
I'm sure there is also a way in the project settings to prevent the closing, I've never looked myself.

I generally leave a breakpoint on the closing brace of main, so that the output of my window is visible while debugging, but Visual Studio will keep the console window open if you start the program without debugging (Ctrl+F5). Alternatively, you could simply ask for input, #MadcapLaugher's fgetc(STDIN); is probably your best bet - though I would add a prompt: "Press any key to continue... "

#include<stdio.h>
int main()
{
printf("Hello World from visual Studio \n");
//to prevent console window temination
system("pause");
return 0;
}

Related

keyboard interrupt routine visual studio C++ console app

I am using VS 2022 Preview to write a C++ console application. I wish to detect a keyboard hit and have my interrupt handler function called. I want the key press detected quickly in case main is in a long loop and therefore not using kbhit().
I found signal() but the debugger stops when the Control-C is detected. Maybe it is a peculiarity of the IDE. Is there a function or system call that I should use?
Edit: I am vaguely aware of threads. Could I spawn a thread that just watches kbd and then have it raise(?) an interrupt when a key is pressed?
I was able to do it by adding a thread. On the target I will have real interrupts to trigger my ISR but this is close enough for algorithm development. It seemed that terminating the thread was more trouble than it was worth so I rationalized that I am simulating an embedded system that does not need fancy shutdowns.
I decided to just accept one character at a time in the phony ISR then I can buffer them and wait and process the whole string when I see a CR, a simple minded command line processor.
// Scheduler.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <Windows.h>
#include <iostream>
#include <thread>
#include <conio.h>
void phonyISR(int tbd)
{
char c;
while (1)
{
std::cout << "\nphonyISR() waiting for kbd input:";
c = _getch();
std::cout << "\nGot >" << c << "<";
}
}
int main(int argc, char* argv[])
{
int tbd;
std::thread t = std::thread(phonyISR, tbd);
// Main thread doing its stuff
int i = 0;
while (1)
{
Sleep(2000);
std::cout << "\nMain: " << i++;
}
return 0;
}

VS Not Prints To The Output Window

I would like to print and see the message in the "Output Window" in Visual Studio 2013. After running this C++ code:
#include <iostream>
using namespace std;
int main(){
cout << "hello world";
}
I cannot see the message in the output window. Instead, a black window in which the message "hello world" is written seems instantly and closes.
I disabled "Redirect all output text to the Immediate window". However, it is still not printing the message.
This behavior is expected, because the program is completing its functions. You can change the code to this:
#include <iostream>
using namespace std;
int main(){
cout << "hello world";
system("PAUSE");
}
Which will make the window pause until you hit a key to continue, but after printing hello world the program is finished running and will close.

main() program won't exit normally

My C++ 2011 main() program for DiGSE is:
int main(int argc, char* argv[]) {
. . .
return EXIT_SUCCESS;
} // this } DOES match the opening { above
It compiles and executes correctly. A print statement immediately before the return outputs normally. However, a Windows 7.1 notification pops up saying "DiGSE.exe has stopped working." It then graciously offers to search the web for a solution.
I tried replacing the return with return 0; exit(0); and nothing so execution falls out the bottom (which, as I understand, is acceptable). However, in all cases I still get the pop-up.
What do I do to get the main() to exit gracefully?
DiGSE is just the name of the Windows 7 executable compiled on MinGW 4.9.2. The "full" program is already stripped down:
int main(int argc, char* argv[]) {
try {
DiGSE::log_init(DiGSE::log_dest_T::console_dest, "dig.log", true,
DiGSE::log_lvl_T::trace_lvl);
}//try
catch (const std::exception& ex) {
std::cerr << FMSG("\n"
"Executing '%1%' raised this exception:\n"
" %2%", % DiGSE::Partition::productName()
% ex.what())
<< std::endl;
return EXIT_FAILURE;
}//exception
catch (...) {
std::cerr << FMSG("\n"
"Executing '%1%' instance raised an unknown exception.",
% DiGSE::Partition::productName())
<< std::endl;
return EXIT_FAILURE;
}//exception
L_INFO(FMSG("'%1% v%2%' terminated normally.",
% DiGSE::Partition::productName()
% DiGSE::Partition::productVersion()))
return EXIT_SUCCESS;
}//main()
The L_INFO() is a logging call, which outputs as it should. The log_init() at the top initializes the log. Commenting out log_init() and L_INFO() has the same result as originally reported.
Program received signal SIGSEGV, Segmentation fault.
0x000000006fc8da9d in libstdc++-6!_ZNSo6sentryC1ERSo ()
from D:\Program Files\mingw-w64\x86_64-4.9.2-posix-seh-rt_v3-rev0\mingw64\bin
\libstdc++-6.dll
This is what gdb returns while mail() is exiting. It does this even with the log_init() and L_LNFO() commented out. So the problem is probably in one of globals of something it's linked to.
It is completely possible for a program to crash after the end of main -- the program isn't over yet. The following items execute after main() returns:
Registered at_exit handlers
Destructors for main()'s own automatic variables, and all variables with static storage duration (globals and function-static) (C++ only)
DllMain(PROCESS_DETACH) code in all dynamic libraries you are using (Windows only)
In addition to that, various events can occur outside your program and cause failures which you might mistake for a failure of your program (especially if your program forks or spawns copies of itself):
SIGCHLD is raised (on *nix). Process handles become signaled and cause wait functions to return (on Windows)
All open handles (file descriptors) get abandoned, and the close handler in the driver is invoked
The other end of connections (pipes, sockets) shift into a disconnected state (reads return 0, writes fail, on *nix SIGHUP may be raised)
I suggest attaching a debugger, set a breakpoint at the end of main, and then single-step through the cleanup code to find out where the failure is occurring. Divide and conquer may also be helpful (cut out some global variables, or all usage of a particular DLL).

How to remove file if application is not running?

Not sure whether this is possible, but I'm creating a file encoding applcation. When a file is decoded, it is saved temporarily in a temp directory, after which it can be opened regularly. However, I actually need to be certain the file is removed as soon as the application that has opened it, has closed it (e.g. has shut down). Otherwise, the decoded (secret) file is just hanging in the temp directory without supervision.
What's more, even when my application itself has been shut down for any reason, I'd like to pass this task on to Windows, if possible. So say the user decodes a file and opens it and then my application is shut down (either normally or abnormally), the decoded file in the temp directory should still be removed as soon as it's not used anymore.
How would I go about this? I've seen tips like FileSystemWatcher and a trivial 'check every second' idea, but if my application is not alive at the moment the decoded file is closed, I'd still like to have the file removed. So I guess I'd need to pass this responbility to Windows, but I'm not sure if that's possible and if so, how.
So how do I remove a file as soon as it's closed if my application isn't running at that particular moment?
Doing this may work:
In the process that creates the file, create it with FileOptions.DeleteOnClose, and with FileShare.ReadWrite (or FileShare.Read if only read access is required from other processes). You may also need FileShare.Delete.
DO NOT let the file close in the main application that created it until the application exits.
In other processes that consume the temporary file, open it with the same file options as the original.
This way, when the last process that has the file open closes, the file will be deleted.
UPDATE:
As noted in the comments, there doesn't seem to be a way in the .NET API to specify both the FIleShare options and the FileOptions.DeleteOnClose. It is possible using straight Win32. I have copied a sample that I tested below. There are 2 programs, one that creates the file, another that consumes it. The only notable difference between the 2 is that the consumer opens the file with OPEN_EXISTING.
Creator
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <iostream>
#include <string>
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE fh = CreateFile(
L"yourFilePath\\tempFile.dat",
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_WRITE|FILE_SHARE_READ|FILE_SHARE_DELETE,
NULL,
CREATE_NEW,
FILE_FLAG_DELETE_ON_CLOSE,
NULL);
if(fh==INVALID_HANDLE_VALUE)
{
std::cerr << "Failed to create file. Error code = " << GetLastError() << std::endl;
return 1;
}
std::cout<< "Hit enter to close.";
std::string inp;
std::getline(std::cin,inp);
CloseHandle(fh);
return 0;
}
Consumer
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <iostream>
#include <string>
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE fh = CreateFile(
L"yourFilePath\\tempFile.dat",
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_WRITE|FILE_SHARE_READ|FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_FLAG_DELETE_ON_CLOSE,
NULL);
if(fh==INVALID_HANDLE_VALUE)
{
std::cerr << "Failed to create file. Error code = " << GetLastError() << std::endl;
return 1;
}
DWORD written;
if(!WriteFile(fh,"Test",4,&written,NULL))
{
std::cerr << "Failed to write data to file. Error code = " << GetLastError() << std::endl;
return 1;
}
std::cout<< "Hit enter to close.";
std::string inp;
std::getline(std::cin,inp);
CloseHandle(fh);
return 0;
}
Use FileOptions.DeleteOnClose.
Things like FileOptions.DeleteOnClose won't help if your media becomes unavailable or the machine gets shut down before the delete occurs. To me this looks very much like an exogenous condition.
Can you stream the decoding to a memory stream rather than to disk and take the whole problem away.

Command prompt in debug mode for Eclipse? (OpenCV + Eclipse + Win7)

I am a beginner for Eclipse. I now have Eclipse C/C++ IDE with OpenCV library running on Windows 7. So far it works after spending hours trying to get it running. But then I realize that Eclipse does not pop up a command prompt as VS2010 does while debugging. And moreover Eclipse's debug mode is just stuck in there and refuse to output anything. But if the code doesn't involve the OpenCV things it works again.
Below is the code I use for testing. It captures images from webcam and output it to the screen. The infinite loop (until you press 'q') makes sure it constantly grabs new inputs from the camera.
I browsed through the workspace and run the exe just compiled and it worked flawlessly. So I don't think there's anything wrong in the code (it's an example code anyway
In brief, can I just pop up a command prompt window in debug mode? And why is Eclipse console stuck when the code involves some OpenCV functions?
#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>
#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
CvCapture *capture = 0;
IplImage *frame = 0;
int key = 0;
/* initialize camera */
capture = cvCaptureFromCAM( 0 );
/* always check */
if ( !capture ) {
printf("Cannot open initialize webcam!\n");
return 1;
}
/* create a window for the video */
cvNamedWindow( "result", CV_WINDOW_AUTOSIZE );
while( key != 'q' ) {
/* get a frame */
frame = cvQueryFrame( capture );
/* always check */
if( !frame ) break;
/* display current frame */
cvShowImage( "result", frame );
/* exit if user press 'q' */
key = cvWaitKey( 1 );
}
/* free memory */
cvDestroyWindow( "result" );
cvReleaseCapture( &capture );
return 0;
}
This is because you have already set the windows 7 system variable PATH to your MinGw/bin and compiled opencv bin directories. So when you run the program from your folder your system automatically take the required binaries from its PATH and the program runs correctly.
I don't know why but Eclipse does not take it directly from the system environment PATH variable. So we have to set it ourself.
go to Preferences > C/C++ (Expand it) > Environment > Add:
"Name:PATH"
"Value:C:\MinGW\bin;C:\opencv_MinGW\bin"
where opencv_MinGW is the folder where I compiled my opencv

Resources