Screwing up \n\r\t by system() - c++

I have read and tried many solutions and nothing solved my problem.
I am generating a dll out of c++ code and want to display the printf() or the std::cout inside of a console window. For testing I just create a .exe out of the c++ code but that is not solving the problem!
I know that system("Pause") is a bad habit, but this is just an easy way to get the same problem. Instead of calling system("Pause") I'm doing a system()-call that is calling the cl.exe and is compiling a dll out of a .c file(Like: system("cl...). The generation of the dll out of the other c file is working without any problems. But after I called the system function for compiling the dll file the printf and std::out are not displaying the right text in the console window.
here is my example code that is screwing up the display of the right characters:
#include "stdafx.h"
#include <iostream>
#include <windows.h>
int _tmain(int argc, _TCHAR* argv[])
{
AllocConsole();
freopen("CONOUT$", "w", stdout);
std::cout << "Everything works fine\n";
// Calling the cl.exe by cmd...
system("Pause");
std::cout << "now its strewd up the newline is not working\n" << std::endl;
FreeConsole();
return 0;
}
Here is a picture of the output:
I tried the fflush before and after calling the system().
So here are my further thoughts:
Could I call the cl.exe by a CreateProcess and would that solve my problem?And when yes, how will I do that and to implement the environment variables out of the batch vcvars32.bat. So I want to create a dll out of a .c located both in the same folder.
Or could write a batch file that is calling the whole cl.exe and vcvars32.bat file process.
Or is there another way to display the values out of a dll instead of calling AllocConsole()?
I hope you can help me maybe I'm missing something!

So in order to try these error on my laptop (because I'm travelling today) I set up the same code at my laptop. Because I forgot to uncheck Security Development Lifecycle (SDL) checks there was an error when calling freopen("CONOUT$", "w", stdout); .Because the error message at building the code inside of visual studio 2015 was:
Severity Code Description Project File Line
Error C4996 'freopen': This function or variable may be unsafe. Consider using freopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. ConsoleApplication1 c:\users\noxious\documents\visual studio 2015\projects\consoleapplication1\consoleapplication1\consoleapplication1.cpp 12
I searched for the function freopen_s and exact at a example of freopen_s I saw the following code Outputting Unicode to Allocated Console Issue:
freopen_s(&stream, "CONOUT$", "w+t", stdout);
I tried this one and acually my problem was solved! BUT it wasn't the freopen_s that solved the problem it was just the inside of it "w+t" so I looked it up and saw that w+ is refering to the following type of access cstdio: freopen:
"w+"
Create an empty file for reading and writing. If a file with the same name already exists its content is erased before it is opened.
So I tried a few combinations and got this resulst:
wt not working
w+t working (but the t is always standard even if you use w+ is the same as w+t
w+ working
So I think I have just to setup an empty file for reading and writing! I will looking further deep into that because I'm not quite sure what is the difference and if it is still solving the problem when using the dll instead of the exe file!
Hope this might help some other people who are trying to solve same errors! But just a "+" was delaying my work now for more than one day!
Edit 5.10.2015:
So I tested this function with the "w+" instead of "w" and it fixed my problem!Even using a dll instead of a generated exe!

It looks like the process is changing the output codepage on the console, then not changing it back when it's done. Not sure why this would happen, but if that's the cause, it should be sufficient to save and restore the codepage:
AllocConsole();
freopen("CONOUT$", "w", stdout);
std::cout << "Everything works fine\n";
// Calling the cl.exe by cmd...
UINT codepage = GetConsoleOutputCP();
system("Pause");
SetConsoleOutputCP(codepage);
std::cout << "Should work now." << std::endl;
FreeConsole();
return 0;
BTW, it might also be screwing up the input codepage. You can use GetConsoleCP() and SetConsoleCP() for that.

Related

Cannot fix an "invalid handle" error in WinAPI when trying to do anything requiring it

I am trying to play around with WinAPI to be able to manipulate the console, mostly just be able to write whatever I want, wherever I want without having to rewrite the whole console. I remember that I once got it to work earlier but that was long ago and I seem to have lost that code... whoops.
Anyway, I remember, that I succeeded with much less effort than what it is taking me now.
I am using this MS Docs page for reference and I remember using it earlier, successfully.
Right now, there is truly only a couple of lines that I am trying to get to work:
#include <windows.h>
#include <iostream>
using namespace std;
int main()
{
HANDLE hndl = GetStdHandle(STD_INPUT_HANDLE);
if (hndl == INVALID_HANDLE_VALUE)
{
cout << "Invalid handle, error " << GetLastError();
return 0;
}
long unsigned int *chars_written = new long unsigned int;
if (!WriteConsoleOutputCharacter(hndl, "mystring", 8, {20, 30}, chars_written))
{
cout << "Could not write, error " << GetLastError();
return 0;
}
return 0;
}
The result is the console window displaying "Could not write, error 6" and then ending the application.
Error 6, according to System Error Codes is "the handle is invalid".
What am I doing wrong? I must be missing something.
It seems to be important that I am trying to work in Code::Blocks.
BONUS: I tried MS Visual Studio with the full WinAPI SDK (some important parts seem to be missing in Code::Blocks) and, while the main problem is the same, the functions in MS Visual Studio don't seem to all fit the official reference I am using, e.g. WriteConsoleOutputCharacter requires an LPCWSTR as its 2nd argument instead of a LPCSTR as mentioned in the source and as works in Code::Blocks. Windows Data Types
Edit: I found that WriteConsoleOutputCharacter is a macro actually, and is defined differently between Code::Blocks and MS Visual Studio, as two different, existing in both versions functions: WriteConsoleOutputCharacterA() and WriteConsoleOutputCharacterW(), which sadly, is not mentioned in the MS Docs.
Thank you in advance,
Maurice.
First of all WriteConsoleOutputCharacter() requires a wide string as argument, while you're passing a normal string "mystring" as argument. To make it a wide literal, you just add the letter L as a prefix - e.g: L"mystring". And the program is giving you an error because the handle you're retrieving is an input handle (STD_INPUT_HANDLE). Meanwhile, if you want to output to the console through a handle you need to retrieve an output handle (STD_OUTPUT_HANDLE).

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

Programmatically Ignore printf

I'm using someones library that printf's out an error message when a connection to a device is unsuccessful.
The library code prints out nothing when a connection is successful.
I periodically check (loop & sleep) to see if a device is connected but I only want to print out when it is connected.
At the moment I get something like:
Waiting for connection... (<-- My print)
Error
Error
Error
Error
Error
Connection successful (<-- My print)
What I want is:
Waiting for connection... (<-- My print)
Connection successful (<-- My print)
How can I programatically ignore a printf?
N.b. I found a similar question Programmatically Ignore Cout but that solution did not work for printf.
I am using Windows.
Can anyone help? (c/c++ novice)
Have you tried something like (before establishing connection):
FILE * myout = stdout;
stdout = fopen ("standard-output-file", "w");
To print something to output you could use then:
fprintf(myout, "format", ...);
Edit: Remember to close the file descriptor afterwards:
fclose(myout);
I was able to get this working under Linux the following way
#include <cstdio>
using namespace std;
int main() {
printf("Start\n");
freopen("/dev/null", "w", stdout);
printf("middle\n");
freopen("/dev/stdin", "w", stdout); // really stdin here!
printf("End\n");
return 0;
}
Under Windows I think there are other names for files (nul and con maybe).
However, this seems to be completely unportable, and, what's worse, this will prevent the users from redirecting your program output to a file, because I explicitly reopen /dev/stdin. There are suggestions that you can use /dev/fd/1 instead of /dev/stdin to mitigate the latter problem, but I have not tested it.
It seems that there is no reliable way, see, e.g. http://c-faq.com/stdio/undofreopen.html
I don't know the absolute solution, but you'll need to use:
freopen("conout$", "w", stderr);
Or something similar, but with "conout$" pseudo-file, which I believe is same as /dev/stdout on Linux.
You may have to use GetStdHandle, AttachConsole etc.
If you are using c++11 and above you can use a simple variadic template without much coding so this overloads printf for all cases and the original one never gets called
template <typename ...Args>
void printf(Args... ...)
{
}

C++ separate command line window?

So I have a GUI program and for some reason it does not let me debug using printf().
When I use printf(), it does not go to the Visual Studio debugger for some reason.
Anyways, I wanted to make my own separate window that opens up when the GUI opens up,
and basically be able to feed information into that console and talk to it.
For example:
void talk(std::string info){
//Add the value of info to the next line in the console
}
Anyone know how to do this?
Basically create a command line and talk to it so I can see output:
CommandLine c;
c.talk("hey!");
You can create a console using AllocConsole to create a console, then write to that explicitly (there are a few methods, GetStdHandle and file write will work). You can also use OutputDebugString to write to the VS output window.
void makeConsole()
{
AllocConsole();
console = GetStdHandle(STD_OUTPUT_HANDLE);
}
void talk(std::string info)
{
WriteFile(console, info.c_str(), info.length()); // To console
OutputDebugString(info.c_str()); // To output window
}
(pseudo-code, functions may not be quite right)
Edit:
If you're writing to the console only through your talk function, this will work fine. If you're using printf/cout throughout your code, you definitely want to use Ben's method (much simpler to use repeatedly).
#peachykeen has half the solution. If you want to make printf and cout work, try this:
AllocConsole();
freopen("CONOUT$", "w", stdout);

How do I print to the debug output window in a Win32 app?

I've got a win32 project that I've loaded into Visual Studio 2005. I'd like to be able to print things to the Visual Studio output window, but I can't for the life of me work out how. I've tried 'printf' and 'cout <<' but my messages stay stubbornly unprinted.
Is there some sort of special way to print to the Visual Studio output window?
You can use OutputDebugString. OutputDebugString is a macro that depending on your build options either maps to OutputDebugStringA(char const*) or OutputDebugStringW(wchar_t const*). In the later case you will have to supply a wide character string to the function. To create a wide character literal you can use the L prefix:
OutputDebugStringW(L"My output string.");
Normally you will use the macro version together with the _T macro like this:
OutputDebugString(_T("My output string."));
If you project is configured to build for UNICODE it will expand into:
OutputDebugStringW(L"My output string.");
If you are not building for UNICODE it will expand into:
OutputDebugStringA("My output string.");
If the project is a GUI project, no console will appear. In order to change the project into a console one you need to go to the project properties panel and set:
In "linker->System->SubSystem" the value "Console (/SUBSYSTEM:CONSOLE)"
In "C/C++->Preprocessor->Preprocessor Definitions" add the "_CONSOLE" define
This solution works only if you had the classic "int main()" entry point.
But if you are like in my case (an openGL project), you don't need to edit the properties, as this works better:
AllocConsole();
freopen("CONIN$", "r",stdin);
freopen("CONOUT$", "w",stdout);
freopen("CONOUT$", "w",stderr);
printf and cout will work as usual.
If you call AllocConsole before the creation of a window, the console will appear behind the window, if you call it after, it will appear ahead.
Update
freopen is deprecated and may be unsafe. Use freopen_s instead:
FILE* fp;
AllocConsole();
freopen_s(&fp, "CONIN$", "r", stdin);
freopen_s(&fp, "CONOUT$", "w", stdout);
freopen_s(&fp, "CONOUT$", "w", stderr);
To print to the real console, you need to make it visible by using the linker flag /SUBSYSTEM:CONSOLE. The extra console window is annoying, but for debugging purposes it's very valuable.
OutputDebugString prints to the debugger output when running inside the debugger.
If you want to print decimal variables:
wchar_t text_buffer[20] = { 0 }; //temporary buffer
swprintf(text_buffer, _countof(text_buffer), L"%d", your.variable); // convert
OutputDebugString(text_buffer); // print
Consider using the VC++ runtime Macros for Reporting _RPTN() and _RPTFN()
You can use the _RPTn, and _RPTFn macros, defined in CRTDBG.H, to
replace the use of printf statements for debugging. These macros
automatically disappear in your release build when _DEBUG is not
defined, so there is no need to enclose them in #ifdefs.
Example...
if (someVar > MAX_SOMEVAR) {
_RPTF2(_CRT_WARN, "In NameOfThisFunc( ),"
" someVar= %d, otherVar= %d\n", someVar, otherVar );
}
Or you can use the VC++ runtime functions _CrtDbgReport, _CrtDbgReportW directly.
_CrtDbgReport and _CrtDbgReportW can send the debug report to three different destinations: a debug report file, a debug monitor (the
Visual Studio debugger), or a debug message window.
_CrtDbgReport and _CrtDbgReportW create the user message for the debug report by substituting the argument[n] arguments into the format
string, using the same rules defined by the printf or wprintf
functions. These functions then generate the debug report and
determine the destination or destinations, based on the current report
modes and file defined for reportType. When the report is sent to a
debug message window, the filename, lineNumber, and moduleName are
included in the information displayed in the window.
If you need to see the output of an existing program that extensively used printf w/o changing the code (or with minimal changes) you can redefine printf as follows and add it to the common header (stdafx.h).
int print_log(const char* format, ...)
{
static char s_printf_buf[1024];
va_list args;
va_start(args, format);
_vsnprintf(s_printf_buf, sizeof(s_printf_buf), format, args);
va_end(args);
OutputDebugStringA(s_printf_buf);
return 0;
}
#define printf(format, ...) \
print_log(format, __VA_ARGS__)
Your Win32 project is likely a GUI project, not a console project. This causes a difference in the executable header. As a result, your GUI project will be responsible for opening its own window. That may be a console window, though. Call AllocConsole() to create it, and use the Win32 console functions to write to it.
I was looking for a way to do this myself and figured out a simple solution.
I'm assuming that you started a default Win32 Project (Windows application) in Visual Studio, which provides a "WinMain" function. By default, Visual Studio sets the entry point to "SUBSYSTEM:WINDOWS". You need to first change this by going to:
Project -> Properties -> Linker -> System -> Subsystem
And select "Console (/SUBSYSTEM:CONSOLE)" from the drop-down list.
Now, the program will not run, since a "main" function is needed instead of the "WinMain" function.
So now you can add a "main" function like you normally would in C++. After this, to start the GUI program, you can call the "WinMain" function from inside the "main" function.
The starting part of your program should now look something like this:
#include <iostream>
using namespace std;
// Main function for the console
int main(){
// Calling the wWinMain function to start the GUI program
// Parameters:
// GetModuleHandle(NULL) - To get a handle to the current instance
// NULL - Previous instance is not needed
// NULL - Command line parameters are not needed
// 1 - To show the window normally
wWinMain(GetModuleHandle(NULL), NULL,NULL, 1);
system("pause");
return 0;
}
// Function for entry into GUI program
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
// This will display "Hello World" in the console as soon as the GUI begins.
cout << "Hello World" << endl;
.
.
.
Result of my implementation
Now you can use functions to output to the console in any part of your GUI program for debugging or other purposes.
You can also use WriteConsole method to print on console.
AllocConsole();
LPSTR lpBuff = "Hello Win32 API";
DWORD dwSize = 0;
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), lpBuff, lstrlen(lpBuff), &dwSize, NULL);
This works for C++ under MSVC, and even for GUI applications when being run via Debugger. It also gets omitted entirely from release builds. It even uses a C++ stringstream for flexible input.
#include <iostream>
#ifdef _MSC_VER
#include "Windows.h"
#endif
#if !defined(NDEBUG) && defined(_MSC_VER)
#define LOG(args) {std::stringstream _ss; _ss << __FILE__ << "#" << __LINE__ << ": " \
<< args << std::endl; OutputDebugString(_ss.str().c_str());}
#else
#define LOG(args)
#endif
Use like:
LOG("some message " << someValue);