I have a simple C++ program to store pressed keys in file.
What works is prinf to show it in console but fprintf to save it in file won't work.
Even fprintf(logx, "TEST"); works only when i delete while cycle.
My code:
int main(){
char c;
FILE *logx;
logx = fopen("mylog2.txt", "w");
fprintf(logx, "TEST");
while (true)
{
Sleep(10);
for (int i = 8; i <= 255; i++)
{
if (GetAsyncKeyState(i) == -32767)
{
switch(i) {
case 96:
fprintf(logx, "%d", 0);
break;
case 97:
fprintf(logx, "%d", 1);
break;
case 98:
fprintf(logx, "%d", 2);
break;
case 99:
fprintf(logx, "%d", 3);
break;
case 100:
fprintf(logx, "%d", 4);
break;
case 101:
printf("%d", 5);
break;
case 102:
printf("%d", 6);
break;
case 103:
printf("%d", 7);
break;
case 104:
printf("%d", 8);
break;
case 105:
printf("%d", 9);
break;
default:
c = char(i);
printf("%c", c);
break;
}
}
}
}
return 0;
}
File is empty after pressing all possible numbers. Not even TEST is written in file (when while cycle is deleted "TEST" is printed).
Thanks for any help or hint.
You must terminate the loop somehow. If you terminate your program with Ctrl-C the FILE I/O buffers will not be flushed and your file will be empty.
Alternatively you can put an fflush(logx); behind every individual fprintf() statement to force the data out to the file. But this is only a last resort as it makes file I/O very slow.
You should also close the file after the loop:
fclose(logx);
Related
i have a question:
(i use winows, visual studio)
i making a program and i need to read keyboard and mouse input istantly so like getch() (because if i use cin i need to press fullstop new line evry time).
i have this:
char p;
while (running) {
if (_kbhit()) {
p = _getch();
switch (p) {
case 'w':
mx = -1;
map(player, mx, 0);
break;
case 'a':
my = -1;
map(player, 0, my);
break;
case 's':
mx = 1;
map(player, mx, 0);
break;
case 'd':
my = 1;
map(player, 0, my);
break;
case 27:
running = false;
break;
}
}
}
the problem is with _getch() i can't read mouse imput.
so how i can get this?
I'm making a Snake game using ANSI escape codes in C++. I want to get the keyboard input and, for example, when I press W then the snake will move up and the direction will be set to U so it will keep moving up until I press another direction key:
void Map::getSnakeMovement(char *path) { ifstream keyboardFile(path, ios::in | ios::binary);
keyboardInput kbInput;
if (!keyboardFile) {
cerr << "Cannot read the keyboard input" << endl;
return;
}
while(1) {
keyboardFile.read((char*)&kbInput, sizeof(keyboardInput));
switch(this->currentDirection) {
case 'L':
this->snake[0].move(this->snake[0].getXPosition() - 1, this->snake[0].getYPosition());
this->isPoint(this->snake[0].getXPosition(), this->snake[0].getYPosition());
this->scoreboard.display();
break;
case 'U':
this->snake[0].move(this->snake[0].getXPosition(), this->snake[0].getYPosition() - 1);
this->isPoint(this->snake[0].getXPosition(), this->snake[0].getYPosition());
this->scoreboard.display();
break;
case 'R':
this->snake[0].move(this->snake[0].getXPosition() + 1, this->snake[0].getYPosition());
this->isPoint(this->snake[0].getXPosition(), this->snake[0].getYPosition());
this->scoreboard.display();
break;
case 'D':
this->snake[0].move(this->snake[0].getXPosition(), this->snake[0].getYPosition() + 1);
this->isPoint(this->snake[0].getXPosition(), this->snake[0].getYPosition());
this->scoreboard.display();
break;
}
if (kbInput.type == 1 && kbInput.value == 1 && kbInput.code != 0) {
switch(kbInput.code) {
case W_KEY:
this->currentDirection = 'U';
break;
case A_KEY:
this->currentDirection = 'L';
break;
case S_KEY:
this->currentDirection = 'D';
break;
case D_KEY:
this->currentDirection = 'R';
break;
}
}
Utils::moveCursor(this->height + 20, 1);
}
keyboardFile.close();
}
But the result is not as expected. Is the read method blocking the flow?
I have written below function and check it using Arduino MEGA. This code is simply read PORTC and filter it's 4bit and according to that bit values, function returns -2 to 13.
#define PDL_1_BRN 37 //PC0
#define PDL_2_GRN 36 //PC1
#define PDL_3_WHT 35 //PC2
#define PDL_4_YEL 34 //PC3
void setup() {
Serial.begin(9600);
pinMode(PDL_1_BRN, INPUT); //use external pullup
pinMode(PDL_2_GRN, INPUT);
pinMode(PDL_3_WHT, INPUT);
pinMode(PDL_4_YEL, INPUT);
}
uint32_t t = 0;
void loop() {
t = micros();
getPedalState();
Serial.println(micros() - t);
}
int8_t getPedalState() {
uint8_t val = 0;
val = PINC & 0x0F;
switch (val) {
case 0x0F:
return 0;
break;
case 0x0B:
return 1;
break;
case 0x09:
return 2;
break;
case 0x01:
return 3;
break;
case 0x05:
return 4;
break;
case 0x0D:
return 5;
break;
case 0x0C:
return 6;
break;
case 0x04:
return 7;
break;
case 0x00:
return 8;
break;
case 0x08:
return 9;
break;
case 0x0A:
return 10;
break;
case 0x02:
return 11;
break;
case 0x06:
return 12;
break;
case 0x0E:
return 13;
break;
case 0x07:
return -1;
break;
case 0x03:
return -2;
break;
}
}
Using separate code I measured PORTC read execution time using micros(). It takes 4uS as I measured.
This code also read the PORTC and then used a switch case to identify port value.
But, this entire function also gets only 4uS to execute all instructions (port reading, masking, switch case).
That means, switch case didn't take at least 1uS to execute.
As I know, swich case start to compare one by one top of the code to bottom of the code. (That means switch case gets more time to return value in bottom of the code.) But, this code gets only 4uS for any value of the PORTC.
Please explain how switch case works in Arduino/C++.
The resolution of the micros function is 4uS. That's why you're seeing the same values. Toggle a pin instead and watch it with an oscilloscope and you'll get a better idea of the actual timing.
I was writing a code to read and write an image file, but my code works fine except for only one fourth of the image is written when using fwrite()...Please help me find out where i've mistaken.Thanks in advance.
PS I'm a newbie in this field.
This is my code for the read and write functions.
Please ignore any silly things I might have coded to get the work done.
#include<iostream>
#include <cstdlib>
#include <cstdio>
#define FALSE 0
#define TRUE 1
int c,numberOfCols,numberOfRows,HighVal,totalPx,header;
int** a;
int doneReading = FALSE;
char * string;
unsigned char * image;
//Read Image
int readImage(char **argv){
FILE * pFile;
pFile = fopen (argv[1],"rt");
if (pFile==NULL) perror ("Error opening file");
else {
string = (char *)calloc(256,1);
while (!(doneReading) && !feof (pFile)) {
c=(char)getc (pFile);
switch(c){
case 'P':
c=(char)getc (pFile);
switch(c){
case '1':
header=1;
std::cout<<".pbm white n black";
break;
case '2':
header=2;
std::cout<<".pgm greyscale";
break;
case '3':
header=3;
std::cout<<".ppm rgb";
break;
}
c=(char)getc (pFile);
if(c==0x0A) ungetc(c,pFile) ;
break;
case '#':
fgets(string,256,pFile);
std::cout<<"File you entered is "<<string<<"\n";
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
ungetc(c,pFile);
fscanf(pFile,"%d %d %d",&(numberOfCols),&(numberOfRows),&(HighVal));
doneReading=TRUE;
std::cout<<"Done";
std::cout<<"\nNo. of columns: "<<numberOfCols<<"\nNo. of Columns: "<<numberOfRows<<"\nMaximum Intensity: "<<HighVal<<"\n";
break;
}
totalPx=numberOfCols*numberOfRows*1;
image=(unsigned char *)malloc(totalPx);
fread(image,1,totalPx,pFile);
}
std::cout<<"Image read from "<<argv[1]<<"...\n";
}
return totalPx;
}
//Write Image
void writeImage(char **argv,int pixels){
FILE *fOut;
fOut=fopen(argv[2],"wt");
if (fOut==NULL) perror ("Error opening file");
else {
fprintf(fOut,"P%d \n%d %d \n%d",header,numberOfCols,numberOfRows,HighVal);
fwrite(image,1,pixels,fOut);
std::cout<<"Image Written on "<<argv[2]<<"...";
}
}
int main (int argc,char **argv)
{
int pixels;
pixels = readImage(argv);
writeImage(argv,pixels);
return 0;
}
Your problem appears to be with the value returned from readImage(). It's returning the number of pixels without taking into account the size of a pixel. This line:
totalPx=numberOfCols*numberOfRows*1;
returns the number of pixels, but a pixel can be 1, 2, 4 or more bytes. Assuming your image data is RGBA, then you need to multiply that by 4 in the call to either writeImage() or fwrite().
I know this queston has been asked multiple times, but still I am unable to figure this out
#include<stdio.h>
#include<getopt.h>
int ch;
int queue_time=60;
int thread_num=4;
char *scheduling_algo="FCFS";
extern char *optarg;
int port=8080;
int debug_flag,h_flag,l_flag;
int main(int argc,char *argv[])
{
while ((ch = getopt(argc, argv, "dhlprtns")) != -1)
switch(ch)
{
case 'd':
debug_flag=atoi(optarg); /* print address in output */
break;
case 'h':
h_flag=atoi(optarg);
break;
case 'l':
l_flag=atoi(optarg);;
break;
case 'p':
port = atoi(optarg);
break;
case 'r':
printf("%s",optarg);
break;
case 't':
queue_time = atoi(optarg);
break;
case 'n':
thread_num = atoi(optarg);
break;
case 's':
scheduling_algo = optarg;
break;
default:
printf("nothing was passed");
}
printf("%d",queue_time);
printf("%d",debug_flag);
printf("%d",h_flag);
printf("%d",l_flag);
}
I am executing my program using the following command
./a.out -d -h -l -t 55
I am getting the core dumped error . I read a few examples on google, but still I am facing this problem. Can anyone please help?
You need to read the man page for getopt()
while ((ch = getopt(argc, argv, "dhlprtns")) != -1)
^^^^^^^^
This does not correspond to the way you are using the arguments. You
want colons ":" after the flags which expect arguments. In your code
"d" is not followed by a colon and yet you seem to want an value for it:
case 'd':
debug_flag=atoi(optarg); /* print address in output */
break;
So what is happening is you are calling atoi(0) and this is seg faulting.
Here's the example from the man page, note how "b" is not followed by a
colon while "f" is.
#include <unistd.h>
int bflag, ch, fd;
bflag = 0;
while ((ch = getopt(argc, argv, "bf:")) != -1) {
switch (ch) {
case 'b':
bflag = 1;
break;
case 'f':
if ((fd = open(optarg, O_RDONLY, 0)) < 0) {
(void)fprintf(stderr,
"myname: %s: %s\n", optarg, strerror(errno));
exit(1);
}
break;
case '?':
default:
usage();
}
}
argc -= optind;
argv += optind;
This may be of use to others: You will also get a segfault if you specify an option letter as both without colon, and with colon eg "dabcd:e" - in this case "d" occurs with and without colon.... and then use that option letter.
It appears getopt and its variants do not check for this conflict and return an error!