Read line on stdin on Windows 10 IoT (Raspberry Pi 2) - c++

I'm new to developing apps on Windows 10 IoT, so I made little test application just to test how to read input from stdin on a console app on a Raspberry Pi 2 running Windows 10.
Now I know that this is not the average use case, but my original app has the purpose to only serve as a demo.
My little code in C++ (for reasons I'm restricted to C++) so far is very simple:
#include "pch.h"
int main(int argc, char **argv) {
char buffer[1024];
std::cin.getline(buffer, 1024);
printf("%s \n", buffer);
}
The problem I face is, that the line
std::cin.getline(buffer, 1024);
seems to be omitted. All the program does is printing an empty line. So there isn't even time to type anything to stdin.
Maybe it's worth mentioning that I'm testing this via a powershell remote session so maybe this has anything to do with it.
My questions are now:
Is it even possible to read a line from stdin? (I guess so)
Am I doing it wright? (Certainly not)
What is the correct/clean way to do so? Where is my error?

Related

Send characters to console application

I have simple console application that runs in terminal window reads and prints character:
int main(int argc, char **argv, char **envp)
{
while (true)
{
char c =getchar();
printf("%c \n",c);
}
}
Now I would like to make test application that could emulate character press in first application terminal.
Which way I should go? What API functions I should use for this purpose?
No need for special APIs or whatever. Since your sample application is only reading from standard input, you can just send stuff to there.
Before running the program in a terminal, check its connected terminal using tty command. Then send data to that tty that tty reports.
Alternatively, grab the PID of your running application and send data to /proc/$PID/fd/0 so you don't need to check for tty.
Just pipe the test data to your process:
echo "some test data" | ./myprogram
(Your example program in the question will read and print each letter from "some test data").
There are plenty of other variations on this. Read about the shell and shell pipelines.

c++ - beep not working (linux)

I'm trying to beep, but I simply can't. I've already tried:
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
cout << '\a' << flush;
return 0;
}
I have also tried using this: http://www.johnath.com/beep/
But simply doesn't beep.
(If I run $ speaker-test -t sine -f 500 -l 2 2>&1 on the terminal, it beeps, but I would like to beep with c++ to study low-level sound programming)
And I would like to be able to control frequency and duration.
Unless you're logged in from the console, cout will not refer to the system console. You need to open /dev/console and send the \a there.
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int s = open ("/dev/console", O_WRONLY);
if (s < 0)
perror ("unable to open console");
else
{
if (write (s, "\a", 1) != 1)
perror ("unable to beep");
}
}
This depends on terminal emulator are you using. KDE's Konsole, for example, doesn't support beeping with buzzer at all AFAICT. First check that echo -e \\a works in your shell. If it doesn't, your C++ code won't work too. You can use xterm — it does support this.
But even in xterm it may not work if you don't have pcspkr (or snd_pcsp) kernel module loaded. This is often the case when distros blacklist it by default. In this case your bet is looking for a terminal which uses your sound card to emit beeps, not PC speaker AKA buzzer.
You're asking about "low level sound generation", typically, the lowest level of sound generation would involve constructing a wave form and passing it to the audio device in an appropriate format. Of course, then it comes out from your sound card rather than the PC speaker. The best advice I can give would be to read up on the APIs associated with pulse audio, alsa, or even the kernel sound drivers. Last time I played with this (~1996), it basically meant allocating an array of samples, and then computing values to put in there that approximated a sine wave with the appropriate frequency and amplitude, then writing that buffer to the output device. There may have even been some calls to ioctl to set the parameters on the device (sample rate, stereo vs. mono, bit rate, etc). If your audio device supports midi commands, it may be easier to send those in some form that is closer to "play these notes for this long using this instrument".
You may find these articles helpful:
https://jan.newmarch.name/LinuxSound/
http://www.linuxjournal.com/article/6735
Have you tried system call in your application?
system("echo -e '\a'");

HTTP Post Response parsing in C++

I am writing puzzle bot, http server which upon hitting , renders a default page with text area to write code similar to http://codepad.org/. When I type in following program.
#include <stdio.h>
int main( int argc, char **argv) {
return 0;
}
I get following response from HTTP POST.
code : %23include+%3Cstdio.h%3E%0D%0Aint+main%28+int+argc%2C+char+**argv%29+%7B%0D%0A++++return+0%3B%0D%0A%7D
lang : C
How Do I parse the information from the key code. I need to write this program in a temporary file and then compile/run.
You need to decode the data, first. You could use this reference .
All spaces are replaces with the sign +, and all numbers after % are special - 2 digit hex encoded numbers - URL encoded special symbols (like +, ,, }, etc.).
For example, you code will be translated to :
#include <stdio.h>\r\nint main( int argc, char **argv) {\r\n return 0;\r\n}
Where \r\n are CRLF, So, from this, you'll finally get:
#include <stdio.h>
int main( int argc, char **argv) {
return 0;
}
which is exactly your code. Then you could write it to your temp file and try to compile it.
Some things, that come to my mind for better application like this:
make it multithreading - you'll be able to handle more than one such request at the same time
add some queues for the received data - don't lose the data that comes, while your program is processing the current request (kinda queue)
of course, synchronize the threads and be careful with that
I think you're going to need IPC (Inter-Process Communication) - to communicate with your compiler's process and extract the errors, it gives you (unless you have some special API, provided for your compiler)
Of course, these are just some advice, that come to my mind. That would be great exercise for any developer - IPC + multithreading + network programming + http! Great :)
Good luck

fopen problem - too many open files

I have a multithreaded application running on Win XP. At a certain stage one of a threads is failing to open an existing file using fopen function. _get_errno function returns EMFILE which means Too many open files. No more file descriptors are available. FOPEN_MAX for my platform is 20. _getmaxstdio returns 512. I checked this with WinDbg and I see that about 100 files are open:
788 Handles
Type Count
Event 201
Section 12
File 101
Port 3
Directory 3
Mutant 32
WindowStation 2
Semaphore 351
Key 12
Thread 63
Desktop 1
IoCompletion 6
KeyedEvent 1
What is the reason that fopen fails ?
EDIT:
I wrote simple single threaded test application. This app can open 510 files. I don't understand why this app can open more files then multithreaded app. Can it be because of file handle leaks ?
#include <cstdio>
#include <cassert>
#include <cerrno>
void main()
{
int counter(0);
while (true)
{
char buffer[256] = {0};
sprintf(buffer, "C:\\temp\\abc\\abc%d.txt", counter++);
FILE* hFile = fopen(buffer, "wb+");
if (0 == hFile)
{
// check error code
int err(0);
errno_t ret = _get_errno(&err);
assert(0 == ret);
int maxAllowed = _getmaxstdio();
assert(hFile);
}
}
}
I guess this is a limitation of your operating system. It can depend on many things: the way the file descriptors are represented, the memory they consume, and so on.
And I suppose there isn't much you can do about it. Perhaps there is some parameter to tweak that limit.
The real question is, do you really need to open that much files simultaneously ? I mean, even if you have 100+ threads trying to read 100+ different files, they probably wont be able to read them at the same time, and you'll probably not get any better result than having, as an example, 50 threads.
It's difficult to be more accurate since we don't know what you try to achieve.
I think in win32 all the crt function will finally endup using the win32 api underneath. So in this case most probably it must be using CreateFile/OpenFile of win32. Now CreatFile/OpenFile api is not meant only for files (Files,Directories,Communication Ports,pipes,mail slots,Drive volumes etc.,). So in a real application depending on the number these resources your max open file may vary. Since you have not described much about the application. This is my first guess. If time permits go through this http://blogs.technet.com/b/markrussinovich/archive/2009/09/29/3283844.aspx

Redirect both cout and stdout to a string in C++ for Unit Testing

I'm working on getting some legacy code under unit tests and sometimes the only way to sense an existing program behavior is from the console output.
I see lots of examples online for how to redirect stdout to another file in C++, but is there a way I can redirect it to an in-memory stream so my tests don't have to rely on the disk?
I'd like to get anything that the legacy code sends to stdout into a std::string so I can easily .find on the output.
Edit
The legacy code is so bad that it users a mixture of cout << .. and printf. Here is what I have so far:
void TestSuite::setUp(void)
{
oldStdoutBuf = std::cout.rdbuf();
std::cout.rdbuf(consoleOutput.rdbuf());
}
void TestSuite::tearDown(void)
{
std::cout.rdbuf(oldStdoutBuf);
}
The problem is that this does not capture output using printf. I would like something that gets both. Any ideas?
std::stringstream may be what you're looking for.
UPDATE
Alright, this is a bit of hack, but maybe you could do this to grab the printf output:
char huge_string_buf[MASSIVE_SIZE];
freopen("NUL", "a", stdout);
setbuf(stdout, huge_string_buffer);
Note you should use "/dev/null" for linux instead of "NUL". That will rapidly start to fill up huge_string_buffer. If you want to be able to continue redirecting output after the buffer is full you'll have to call fflush(), otherwise it will throw an error. See std::setbuf for more info.
You can use freopen(..., stdout) and then dump the file into memory or a std::string.
This may be an alternative:
char bigOutBuf[8192];
char savBuf[8192];
fflush(stdout);
setvbuf(stdout,bigOutBuf,IOFBF,8192);//stdout uses your buffer
//after each operation
strncpy(savBuf,bigOutBuf,8192);//won't flush until full or fflush called
//...
//at long last finished
setbuf(stdout,NULL);//reset to unnamed buffer
This just intercepts the buffered output, so still goes to console or wherever.
Hope this helps.
Try sprintf, that's more efficient.
int i;
char str[] = "asdf";
char output[256];
sprintf(output, "asdfasdf %s %d\n", str, i);