C - segmentation fault on long running while loop - c

I wrote small daemon for rotating screen on Thinkpad X41 convertible laptop using built-in motion sensor (used by harddisk active protection system) or manually by button. Program works very well, but after some amount of time (5 to 15 minutes) will crash with segfault.
I know there are lot of scripts on the internet to do this written in bash or python, but none of them suit my needs and vision how should program work.
I know that for example mentioned bash is probably better for this, but I have zero experiences with it compared to C In which I have at least minimal basic experiences from few high school lessons, so I choose this.
here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define TRUE 1
#define FALSE 0
#define NIL -1
#define XRANDR_GREP_COMMAND "xrandr -q --verbose|grep LVDS1|cut -b37-37"
#define DAEMON_LOCK_FILE "/dev/shm/thinkrotate.lock"
#define DAEMON_STATE_FILE "/dev/shm/thinkrotate.st"
#define SWIVEL_STATE_FILE "/sys/devices/platform/thinkpad_acpi/hotkey_tablet_mode"
#define GYRO_STATE_FILE "/sys/devices/platform/hdaps/position"
#define BUBBLE_TERMINATED "notify-send 'Ukončenie programu' 'ThinkRotate démon dostal príkaz na ukončenie'"
#define BUBBLE_SWIVEL_DOWN "notify-send 'Notebook v tablet móde' 'Veko bolo sklopené, aktivovaná automatická rotácia'"
#define BUBBLE_SWIVEL_UP "notify-send 'Notebook v štandartnom režime' 'Rotácia je deaktivovaná'"
#define BUBBLE_RETURN_POSITION "notify-send 'Automatická rotácia zapnutá' 'Pre vypnutie automatickej rotácie obrazu stlačte tlačítko rotácie.'"
#define BUBBLE_START_MANUAL_ROTATION "notify-send 'Automatická rotácia vypnutá' 'Rotácia bude zapnutá znovu až pri návrate do tejto polohy, dovtedy na otáčanie obrazu používajte tlačidlo.'"
#define SWIVEL_DOWN_COMMANDS ""
#define SWIVEL_UP_COMMANDS ""
#define WIDTH_COMMANDS ""
#define HEIGHT_COMMANDS ""
int get_lock(void) {
int fdlock;
struct flock fl;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 1;
if((fdlock = open(DAEMON_LOCK_FILE, O_WRONLY|O_CREAT, 0666)) == -1) { return 0; }
if(fcntl(fdlock, F_SETLK, &fl) == -1) { return 0; }
return 1;
}
int next_rotation(int direction) {
int next;
int pos;
pos = current_pos();
if (direction == 1) {
switch (pos) {
case 0:
next = 1;
break;
case 1:
next = 2;
break;
case 2:
next = 3;
break;
case 3:
next = 0;
break;
}
} else if (direction == 2) {
switch (pos) {
case 0:
next = 3;
break;
case 1:
next = 0;
break;
case 2:
next = 1;
break;
case 3:
next = 2;
break;
}
}
return next;
}
int current_pos(void) {
FILE *frotpos;
char rotpos;
int pos;
frotpos = popen(XRANDR_GREP_COMMAND, "r");
fscanf(frotpos, "%c", &rotpos);
fclose(frotpos);
switch (rotpos) {
case 110:
pos = 0;
break;
case 108:
pos = 1;
break;
case 105:
pos = 2;
break;
case 114:
pos = 3;
break;
}
return pos;
}
void rotate(int poz) {
char buff[32];
if ((poz == 2)||(poz == 0)) {
system(WIDTH_COMMANDS);
} else {
system(HEIGHT_COMMANDS);
}
sprintf(buff, "xrandr -o %i", poz);
system(buff);
}
int main(int argc, char *argv[]) {
if(!get_lock()) {
if (argc >= 2) {
int cmd;
FILE *fparams;
fparams = fopen(DAEMON_STATE_FILE, "w");
if (!strncmp(argv[1], "r", 1)) { cmd = 1; }
else if (!strncmp(argv[1], "l", 1)) { cmd = 2; }
else if (!strncmp(argv[1], "k", 1)) { cmd = 0; }
fprintf(fparams, "%i", cmd);
fclose(fparams);
}
return 1;
}
int autorotate = TRUE;
int prevmode = NIL;
FILE *fstate;
int tabletmode;
FILE *fgyrovals;
char gyroval_x[5];
char gyroval_y[5];
int x;
int y;
FILE *fargs;
int argum = NIL;
int next_p;
int prev_p = current_pos();
int last_auto_p = NIL;
while (TRUE) {
fstate = fopen(SWIVEL_STATE_FILE, "r");
fscanf(fstate, "%d", &tabletmode);
if (fargs = fopen(DAEMON_STATE_FILE, "r")) {
if (fscanf(fargs, "%d", &argum) == NIL) { argum = NIL; }
}
fargs = fopen(DAEMON_STATE_FILE, "w");
fclose(fargs);
fclose(fstate);
if (argum == 0) {
system(BUBBLE_TERMINATED);
return 1;
}
if (prevmode != tabletmode) {
if (tabletmode) {
system(BUBBLE_SWIVEL_DOWN);
system(SWIVEL_DOWN_COMMANDS);
} else {
system(BUBBLE_SWIVEL_UP);
system(SWIVEL_UP_COMMANDS);
rotate(0);
}
}
if (tabletmode) {
if (argum == 1 || argum == 2) {
next_p = next_rotation(argum);
if (next_p == last_auto_p) {
rotate(next_p);
autorotate = TRUE;
last_auto_p = NIL;
system(BUBBLE_RETURN_POSITION);
} else if ((autorotate)&&(current_pos() == last_auto_p)) {
autorotate = FALSE;
system(BUBBLE_START_MANUAL_ROTATION);
} else {
if (autorotate) {
system(BUBBLE_START_MANUAL_ROTATION);
last_auto_p = current_pos();
} else {
rotate(next_p);
}
autorotate = FALSE;
}
}
if (autorotate) {
fgyrovals = fopen(GYRO_STATE_FILE, "r");
fscanf(fgyrovals, "(%4[^,], %4[^)]", &gyroval_x, &gyroval_y);
fclose(fgyrovals);
x = atoi(gyroval_x);
y = atoi(gyroval_y) * (-1);
if (y < 465) {
if (x < 210) {
next_p = 1;
} else if (x > 425) {
next_p = 3;
} else {
next_p = 2;
}
} else if (y > 525) {
if (x < 210) {
next_p = 1;
} else if (x > 425) {
next_p = 3;
} else {
next_p = 0;
}
} else {
if (x < 305) {
next_p = 1;
} else if (x > 345) {
next_p = 3;
}
}
if (next_p != prev_p) {
rotate(next_p);
prev_p = next_p;
}
}
} else {
if (argum == 1 || argum == 2) {
system(BUBBLE_SWIVEL_UP);
}
}
prevmode = tabletmode;
sleep(1);
}
return 0;
}

Thanks to comment of user "inspired". Now the program is running more than a hour without segfault.
if (fargs = fopen(DAEMON_STATE_FILE, "r")) {
if (fscanf(fargs, "%d", &argum) == NIL) { argum = NIL; }
fclose(fargs);
}
fargs = fopen(DAEMON_STATE_FILE, "w");
fclose(fargs);
As said, file should be closed before opened next time for writing.

Related

SDL with C - Blocks remains after being played

I have been working on a game that is a Stacker. Everything works fine, but after you have played and started over the blocks from the previous game still remain there.
Could anyone help me with this problem?
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include <SDL/SDL_mixer.h>
#include <stdio.h>
#include <stdlib.h>
#define BASE_TIME_INTERVAL 80
#define SPEED_INCREASE 1.03
#define GAME_ROWS 15
#define GAME_COLUMNS 7
#define MIN(a, b) ((a < b) ? a : b)
#define MAX(a, b) ((a > b) ? a : b)
int array_matrix[GAME_ROWS][GAME_COLUMNS];
//void save();
int credit = 0;
int in = 0;
int out = 0;
int inGame = 0;
static SDL_Surface *screen;
//Sprites
static SDL_Surface *square;
static SDL_Surface *background;
static SDL_Surface *grid;
static SDL_Surface *main_ui;
static SDL_Surface *award;
//Text Credits Sprites
static SDL_Surface *credits;
static SDL_Surface *number;
//Sounds
Mix_Chunk *soundPlace = NULL;
Mix_Chunk *soundGameOver = NULL;
Mix_Chunk *soundCredit = NULL;
FILE * fptr;
void print_board() {
int i, j;
SDL_Rect src, dest;
for (i = 0; i < 15; i++) {
for (j = 0; j < 7 ; j++) {
if (array_matrix[i][j] == 1) {
src.x = 0;
src.y = 0;
src.w = 65;
src.h = 65;
dest.x = j * 67 + 227;
dest.y = i * 67 + 240;
dest.w = 65;
dest.h = 65;
SDL_BlitSurface(square, &src, screen, &dest);
}
}
}
}
void update_board(int x_pos, int length, int level) {
int underflow_ammt = length - 1;
int j;
if (x_pos < underflow_ammt)
length = length - (underflow_ammt - x_pos);
x_pos = MAX(0, x_pos-underflow_ammt);
for (j = 0; j < GAME_COLUMNS; j++)
array_matrix[GAME_ROWS - level][j] = 0;
for (j = x_pos; j < x_pos + length; j++) {
array_matrix[GAME_ROWS - level][MIN(j, GAME_COLUMNS-1)] = 1;
}
}
int get_new_length(int level) {
int i;
int length = 0;
for (i = 0; i < GAME_COLUMNS; i++) {
if (array_matrix[GAME_ROWS - level][i] == 1) {
length++;
if (level != 1) {
if (array_matrix[GAME_ROWS - (level - 1)][i] != 1) {
array_matrix[GAME_ROWS - level][i] = 0;
length--;
}
}
}
if ((level == 4 && length == 3) || (level == 10 && length == 2)) {
length--;
}
}
return length;
}
void draw_background(){
SDL_BlitSurface(background, NULL, screen, NULL);
SDL_BlitSurface(main_ui, NULL, screen, NULL);
SDL_BlitSurface(award, NULL, screen, NULL);
SDL_BlitSurface(grid, NULL, screen, NULL);
}
void draw_credits(){
SDL_Rect destCredits;
SDL_Rect destNumber;
switch (credit)
{
case 0:
number = IMG_Load("assets/0.png");
break;
case 1:
number = IMG_Load("assets/1.png");
break;
case 2:
number = IMG_Load("assets/2.png");
break;
case 3:
number = IMG_Load("assets/3.png");
break;
case 4:
number = IMG_Load("assets/4.png");
break;
case 5:
number = IMG_Load("assets/5.png");
break;
case 6:
number = IMG_Load("assets/6.png");
break;
case 7:
number = IMG_Load("assets/7.png");
break;
case 8:
number = IMG_Load("assets/8.png");
break;
case 9:
number = IMG_Load("assets/9.png");
break;
}
if (number == NULL) {
printf("Unable to load number png.\n");
}
destCredits.x = 300;
destCredits.y = 1300;
destNumber.x = 550;
destNumber.y = 1305;
SDL_BlitSurface(credits, NULL, screen, &destCredits);
SDL_BlitSurface(number, NULL, screen, &destNumber);
}
void game_loop() {
int time_delay = BASE_TIME_INTERVAL;
int left_or_right = 1;
int current_level = 1;
int length = 3;
int x_pos = 0;
int quit = 0;
int underflow_ammt = length - 1;
SDL_Event event;
while (!quit) {
while (SDL_PollEvent(&event)) {
switch(event.type) {
case SDL_KEYDOWN:
if (event.key.keysym.sym == SDLK_SPACE && inGame == 1) {
length = get_new_length(current_level);
underflow_ammt = length - 1;
if (current_level >= 15 || length == 0) {
Mix_PlayChannel( -1, soundGameOver, 0 );
inGame = 0;
time_delay = BASE_TIME_INTERVAL;
left_or_right = 1;
current_level = 1;
length = 3;
x_pos = 0;
underflow_ammt = length - 1;
}
else{
Mix_PlayChannel( -1, soundPlace, 0 );
current_level++;
time_delay = time_delay/SPEED_INCREASE;
}
}
if (event.key.keysym.sym == SDLK_2 && credit < 9){
credit++;
in++;
save();
Mix_PlayChannel( -1, soundCredit, 0 );
}
if (event.key.keysym.sym == SDLK_1 && credit > 0 && inGame == 0){
credit--;
out++;
save();
Mix_PlayChannel( -1, soundCredit, 0 );
inGame = 1;
}
if (event.key.keysym.sym == SDLK_ESCAPE){
quit = 1;
exit(0);
}
break;
case SDL_QUIT:
quit = 1;
exit(0);
break;
}
}
if (!quit) {
SDL_FillRect(screen, NULL, 0x000000);
if (x_pos >= GAME_COLUMNS + (underflow_ammt - 1))
left_or_right = -1;
if (x_pos <= 0)
left_or_right = 1;
update_board(x_pos, length, current_level);
draw_background();
if (inGame == 1)
print_board();
draw_credits();
SDL_Flip(screen);
x_pos = x_pos + left_or_right;
SDL_Delay(time_delay);
}
}
}
/*
void save(){
fptr = fopen("data.xml", "w");
fprintf(fptr,"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
fprintf(fptr,"<Data>\n");
fprintf(fptr," <credits>%d</credits>\n",credit);
fprintf(fptr," <IN>%d</IN>\n",in);
fprintf(fptr," <OUT>%d</OUT>\n",out);
fprintf(fptr,"</Data>\n");
fclose(fptr);
}
*/
void init(){
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
printf("Unable to initialize SDL: %s\n", SDL_GetError());
}
screen = SDL_SetVideoMode(768, 1366, 16, SDL_DOUBLEBUF | SDL_HWSURFACE | SDL_FULLSCREEN);
if (screen == NULL) {
printf("Unable to set video mode: %s\n", SDL_GetError());
}
int imgFlags = IMG_INIT_PNG;
if( !( IMG_Init( imgFlags ) & imgFlags ) )
{
printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
}
if (SDL_Init(SDL_INIT_AUDIO) < 0){
printf("Unable to set audio mode: %s\n", SDL_GetError());
}
//Initialize SDL_mixer
if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 )
printf( "SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError());
}
void loadMedia(){
background = IMG_Load("assets/background.png");
if (background == NULL)
printf("Unable to load background png.\n");
square = IMG_Load("assets/square.png");
if (square == NULL)
printf("Unable to load square png.\n");
credits = IMG_Load("assets/credits.png");
if (credits == NULL)
printf("Unable to load credits png.\n");
grid = IMG_Load("assets/grid.png");
if (grid == NULL)
printf("Unable to load grid png.\n");
main_ui = IMG_Load("assets/main_ui.png");
if (main_ui == NULL)
printf("Unable to load main_ui png.\n");
soundPlace = Mix_LoadWAV("assets/place.wav");
if(soundPlace == NULL)
printf( "Failed to load place sound effect! SDL_mixer Error: %s\n", Mix_GetError() );
soundGameOver = Mix_LoadWAV("assets/gameover.wav");
if(soundGameOver == NULL)
printf( "Failed to load gameover sound effect! SDL_mixer Error: %s\n", Mix_GetError() );
soundCredit = Mix_LoadWAV("assets/credit.wav");
if( soundCredit == NULL )
printf( "Failed to load credit sound effect! SDL_mixer Error: %s\n", Mix_GetError() );
}
void close(){
SDL_FreeSurface(square);
SDL_FreeSurface(background);
SDL_FreeSurface(credits);
SDL_FreeSurface(grid);
SDL_FreeSurface(main_ui);
SDL_FreeSurface(number);
Mix_FreeChunk(soundPlace);
Mix_FreeChunk(soundGameOver);
Mix_FreeChunk(soundCredit);
Mix_Quit();
IMG_Quit();
SDL_Quit();
}
int main(int argc, char *argv[])
{
init();
loadMedia();
game_loop();
close();
return 0;
}
I using:
SDL 1.2.15
SDL_image 1.2.12
SDL_mixer 1.2.12

Get Key State in linux C

OK ive searched about for quite some time now but i simply cannot find a replacement for the GetKeyState() function in linux. All i need and want is to simply poll the arrow keys, and if they are pressed, execute something. My home PC is linux based and my students' PC is windows based, so when i worked in that, i wrote this code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <dos.h>
#include <windows.h>
int x; int y, redraw;
int i; int l, xm, ym, op, as, b, ab;
short int display[10][10];
void draw() {
if (redraw == 1) {
system("cls");
while (l < 10) {
while (i<10) {
if (display[i][l] == 0) { printf("="); }
if (display[i][l] == 1) { printf("X"); }
if (display[i][l] == 2) { printf("w"); }
if (display[i][l] == 3) { printf("0"); }
if (display[i][l] == 4) { printf("#"); }
if (display[i][l] == 5) { printf("M"); }
if (display[i][l] == 6) { printf("H"); }
if (display[i][l] == 7) { printf("8"); }
printf("|");
i++;
}
i = 0;
printf("\n");
printf("-+-+-+-+-+-+-+-+-+-+");
printf("\n");
l++;
}
l = 0;
redraw = 0;
}
}
void getkeys() {
while (b == 0) {
if (GetKeyState(VK_LEFT) & 0x8000)
{
xm = -1;
b = 1;
}
if (GetKeyState(VK_RIGHT) & 0x8000)
{
xm = 1;
b = 1;
}
if (GetKeyState(VK_UP) & 0x8000)
{
ym = -1;
b = 1;
}
if (GetKeyState(VK_DOWN) & 0x8000)
{
ym = 1;
b = 1;
}
if (GetKeyState(VK_BACK) & 0x8000)
{
op = -1;
b = 1;
}
if (GetKeyState(VK_RETURN) & 0x8000)
{
op = 1;
b = 1;
}
} b = 0; redraw = 1;
}
void cursor() {
display[x][y] = as;
x = x + xm;
xm = 0;
y = y + ym;
ym = 0;
if (x >9) { x = 0; }
if (y >9) { y = 0; }
if (x <0) { x = 9; }
if (y <0) { y = 9; }
ab = display[x][y];
as = ab;
if (as == 0) {
display[x][y] = 4;
}
if (as == 1) {
display[x][y] = 5;
}
if (as == 2) {
display[x][y] = 6;
}
if (as == 3) {
display[x][y] = 7;
}
Sleep(100);
}
void main()
{
while (i < 10) {
while (l<10) { display[l][i] = rand() % 4; l++; } l = 0; i++;
}
redraw = 1;
while (1) {
draw();
getkeys();
b = 0;
cursor();
}
}
now this basically prints an array and a cursor on it, but it does use the GetKeyState() function and i just can not find an alternative to it on linux. So is there any simple alternative to the mentioned function and is it possible to make the source code multiplatform somehow? Thanks in advance.

Only printing last line of txt file when reading into struct array in C

I am reading from a txt file into an array of structures. Example txt:
-4.5 -1 0 0
4.0 1 0 0
8 0 1 2
12.1 0 -6 1
-3.2 2.5 -3.0 4
The 4 values of each line correspond to the 4 values in the structure. The file may contain up to 100 lines (MAX is defined as 100). With the following code I am trying to store each line into the respective index of the struct array and then print:
FILE *fileName = NULL;
typedef struct chargeData_struct {
double Q, x, y, z;
} ChargeData;
ChargeData values[MAX], *p = values;
fileName = fopen("charge2.txt", "r");
if (fileName == NULL)
{
printf("ERROR: Could not open file.");
}
int k = 0;
while (fscanf(fileName, "%lf %lf %lf %lf", &p[k].Q, &p[k].x, &p[k].y, &p[k].z) != EOF);
{
printf("%f %f %f %f\n", p[k].Q, p[k].x, p[k].y, p[k].z);
k++;
}
fclose(fileName);
However, only the last line of the txt file is printed. Is the same index of the struct array being overwritten each time?
You are using an extra semicolon which makes all the trouble, here:
while (fscanf(...) != EOF);
{
...
Remove it and you should be fine.
What happens with your code is that while(..); is equivalent to this:
while(...)
{
; // do nothing
}
thus does not enter the body (the one you think is the body) of your loop (since the actual body does nothing). However scanf() continues to parse the file, and then this section of your code executes:
{
printf("%f %f %f %f\n", p[k].Q, p[k].x, p[k].y, p[k].z);
k++;
}
independently, where the curly braces are treated like they wanted to state scope.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define LINE_BUFFER_LEN (512)
#define RESERVE_NEWLINDE 0
#define AUTO_FILTER_NEWLINDE 1
typedef int (* LINE_READER)(char * pstrLine, int uiBufferLen, void * pvData);
typedef struct st_HW_SSP_CONFIG
{
const char * pstrConfigPath;
LINE_READER pfLineReader;
FILE * pstFile;
void * pvData;
int CurrentLine;
int Flag;
} CONFIG_ST;
int CloseConfig(CONFIG_ST * pstConfig)
{
if (!pstConfig)
{
// record error
return -1;
}
if (fclose(pstConfig->pstFile))
{
// record error
}
return 0;
}
int OpenConfigFile(const char * pstrFilePath, CONFIG_ST * pstConfig)
{
FILE * pstFile = NULL;
if ((!pstrFilePath) || (!pstConfig))
{
return -1;
}
pstFile = fopen(pstrFilePath, "r");
if (!pstFile)
{
return -1;
}
pstConfig->pstFile = pstFile;
pstConfig->pstrConfigPath = pstrFilePath;
pstConfig->Flag = RESERVE_NEWLINDE;
return 0;
}
int IsNullStr(const char *pcStr)
{
const char *pcTmp = pcStr;
while ('\0' != *pcTmp)
{
if (!isspace(*pcTmp))
{
return 0;
}
pcTmp++;
}
return 1;
}
int IsEffectiveLine(char acFileLineBuffer[LINE_BUFFER_LEN])
{
if (0 == strlen(&acFileLineBuffer[0]))
{
return 0;
}
if ('#' == acFileLineBuffer[0]) // strip as a comment line
{
return 0;
}
if (IsNullStr(&acFileLineBuffer[0]))
{
return 0;
}
return 1;
}
void FilterNewLine(char* pcLine, int MaxNumLen)
{
int uiLen = strlen(pcLine);
if (uiLen > 1)
{
if ('\n' == pcLine[uiLen - 1])
{
pcLine[uiLen - 1] = '\0';
if (uiLen > 2)
{
if ('\r' == pcLine[uiLen - 2])
{
pcLine[uiLen - 2] = '\0';
}
}
}
}
return;
}
int ReadConfigFile(CONFIG_ST * pstConfig)
{
char acFileLineBuffer[LINE_BUFFER_LEN] = {0};
char * pstrRead = NULL;
int Ret = 0;
if (!pstConfig)
{
return -1;
}
if ((!pstConfig->pstFile) || (!pstConfig->pfLineReader))
{
return -1;
}
rewind(pstConfig->pstFile);
pstConfig->CurrentLine = 0;
do
{
memset((void *)&acFileLineBuffer[0], 0, LINE_BUFFER_LEN);
pstrRead = fgets(&acFileLineBuffer[0], LINE_BUFFER_LEN - 1, pstConfig->pstFile);
if (pstrRead)
{
pstConfig->CurrentLine ++;
if (0 == IsEffectiveLine(acFileLineBuffer))
{
continue;
}
if (AUTO_FILTER_NEWLINDE == pstConfig->Flag)
{
FilterNewLine(acFileLineBuffer, LINE_BUFFER_LEN - 1);
}
if (pstConfig->pfLineReader)
{
Ret = pstConfig->pfLineReader(&acFileLineBuffer[0],
LINE_BUFFER_LEN,
pstConfig->pvData);
if (Ret)
{
break;
}
}
}
}
while (pstrRead);
return Ret;
}
int ReadConfigFileEx(const char * pFilePath,
LINE_READER pfReader,
void * pData, int Flag)
{
int Ret = 0;
CONFIG_ST stConfig = {0};
Ret = OpenConfigFile(pFilePath, &stConfig);
if (Ret)
{
return Ret;
}
stConfig.pfLineReader = pfReader;
stConfig.pvData = pData;
stConfig.Flag = Flag;
Ret = ReadConfigFile(&stConfig);
CloseConfig(&stConfig);
return Ret;
}
int StringSplit(char *pcStr, char cFlag,
char * pstArray[], int MaxNum,
int *pNum)
{
char * pcStrTemp = 0;
unsigned int uiIndex = 0;
pcStrTemp = pcStr;
while (pcStrTemp)
{
pstArray[uiIndex] = pcStrTemp;
pcStrTemp = strchr(pcStrTemp, cFlag);
if (pcStrTemp)
{
*pcStrTemp = '\0';
pcStrTemp ++;
uiIndex ++;
}
if (uiIndex >= MaxNum)
{
break;
}
}
if (0 != MaxNum)
{
*pNum = uiIndex >= MaxNum ? (MaxNum - 1) : uiIndex;
}
else
{
*pNum = 0;
}
return 0;
}
int MyLineReader(char * pstrLine, int uiBufferLen, void * pvData)
{
printf("Read line:[%s]\r\n", pstrLine);
char *pArray[8] = {0};
int Num = 0;
int index = 0;
StringSplit(pstrLine, ' ', pArray, 8, &Num);
for (index = 0; index <= Num; index ++)
{
printf("Get value :[%s]\r\n", pArray[index]);
}
return 0;
}
int main(int argc, char * argv[])
{
int ret = 0;
if (argc != 2)
{
printf("Please input file to read.\r\n");
return 0;
}
ret = ReadConfigFileEx(argv[1], MyLineReader, NULL, AUTO_FILTER_NEWLINDE);
if (ret)
{
printf("Open file error.\r\n");
}
return 0;
}

Pointers Binary Tree Maze Solver in C

I need to create a Robot Simulator programmed in C. The Robot has to find the Exit of a 2d labirinth using a Recursive Backtracker algorithm, i understood how does this algorithm work but i don't know how to implement it. I Think i can use a Binary Tree using Pointers but i don't know how to do this, can you try to explain it to me?
This is the program that i've created, now the Robot is entering a loop because of the method that changes direction
#ifdef __unix__
#include <unistd.h>
#elif defined _WIN32
#include <windows.h>
#define sleep(x) Sleep(1000 * x)
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void goUp();
void goDown();
void goLeft();
void goRight();
typedef struct robot {
int direction;
bool is_moving;
}robot;
typedef struct room {
robot robot;
bool is_robot;
int obstacle;
}room;
room Room[20][20];
int r = 12;
int c = 10;
void generation(room matrix[20][20])
{
srand(time(NULL));
int x,i,j;
x=0;
for(i=0;i<20;i++)
{
for(j=0;j<20;j++)
{
matrix[i][j].is_robot=false;
x=rand()%100+1;
if(x==1||x==50||x==100)
{
matrix[i][j].obstacle=1;
}
else
{
matrix[i][j].obstacle=0;
}
}
}
}
void print_matrix(room matrix[20][20])
{
int i,j;
for(i=0;i<20;i++)
{
for(j=0;j<20;j++)
{
if(matrix[i][j].obstacle==0)
{
if(matrix[i][j].is_robot==true)
{
printf("I");
}
else
{
printf(" ");
}
}
else
{
if(matrix[i][j].is_robot==true)
{
printf("I");
}
else
{
printf("o");
}
}
}
printf("\n");
}
}
bool changeDirection(room Room[20][20],int i,int j)
{
if(Room[i][j].robot.direction == 1)
{
if(Room[i-1][j].obstacle == 1 || i-1 == 0)
{
if(Room[i+1][j].obstacle == 1 || i+1 == 19)
{
Room[i][j].robot.direction = 2;
return true;
}
else
{
Room[i][j].robot.direction = 4;
return true;
}
}
else
{
Room[i][j].robot.direction = 3;
return true;
}
}
if(Room[i][j].robot.direction == 2)
{
if(Room[i-1][j].obstacle == 1 || i-1 == 0)
{
if(Room[i+1][j].obstacle == 1 || i+1 == 19)
{
Room[i][j].robot.direction = 1;
return true;
}
else
{
Room[i][j].robot.direction = 4;
return true;
}
}
else
{
Room[i][j].robot.direction = 3;
return true;
}
}
if(Room[i][j].robot.direction == 3)
{
if(Room[i][j+1].obstacle == 1 || j+1 == 19)
{
if(Room[i][j-1].obstacle == 1 || j-1 == 0)
{
Room[i][j].robot.direction = 4;
return true;
}
else
{
Room[i][j].robot.direction = 2;
return true;
}
}
else
{
Room[i][j].robot.direction = 1;
return true;
}
}
if(Room[i][j].robot.direction == 4)
{
if(Room[i][j+1].obstacle == 1 || j+1 == 19)
{
if(Room[i][j-1].obstacle == 1 || j-1 == 0)
{
Room[i][j].robot.direction = 3;
return true;
}
else
{
Room[i][j].robot.direction = 2;
return true;
}
}
else
{
Room[i][j].robot.direction = 1;
return true;
}
}
}
void goRight()
{
c=c+1;
Room[r][c].robot.direction=1;
Room[r][c].is_robot=true;
Room[r][c-1].is_robot=false;
}
void goLeft()
{
c=c-1;
Room[r][c].robot.direction=2;
Room[r][c].is_robot=true;
Room[r][c+1].is_robot=false;
}
void goUp()
{
r=r-1;
Room[r][c].robot.direction=3;
Room[r][c].is_robot=true;
Room[r+1][c].is_robot=false;
}
void goDown()
{
r=r+1;
Room[r][c].robot.direction=4;
Room[r][c].is_robot=true;
Room[r-1][c].is_robot=false;
}
int main()
{
generation(Room);
Room[r][c].robot.direction = 1;
Room[r][c].robot.is_moving = true;
Room[r][c].is_robot = true;
do
{
Room[r][c].robot.is_moving = true;
if (Room[r][c].robot.direction == 1 && Room[r][c].robot.is_moving == true) // destra
{
if(Room[r][c +1].obstacle == 1 || c+1 == 19)
{
changeDirection(Room,r,c);
}
else
{
goRight();
}
}
if (Room[r][c].robot.direction == 2 && Room[r][c].robot.is_moving == true) // sinistra
{
if(Room[r][c -1].obstacle == 1 || c-1 == 0)
{
changeDirection(Room,r,c);
}
else
{
goLeft();
}
}
if (Room[r][c].robot.direction == 3 && Room[r][c].robot.is_moving == true) // su
{
if(Room[r-1][c].obstacle == 1 || r-1 == 0)
{
changeDirection(Room,r,c);
}
else
{
goUp();
}
}
if (Room[r][c].robot.direction == 4 && Room[r][c].robot.is_moving == true) // giu
{
if(Room[r+1][c].obstacle == 1 || r+1 == 19)
{
changeDirection(Room,r,c);
}
else
{
goDown();
}
}
print_matrix(Room);
sleep(0.1);
system("cls");
}
while(1);
print_matrix(Room);
}
I'm having a hard time understanding how a binary tree would be useful in finding a path in a labyrinth (maybe it's used to represent the labyrinth?) but maybe I'm blind. I would simply make a 2d int array and let 0 mean the position is blocked (there's a wall there or something) and 1 mean it's open (you can move there). The brute force backtrack procedure, going off orthogonal movement (left, right, up, down) would be:
f(x,y){
// you found the place your want to go to
if (x,y) is (destinationX,destinationY)
return true
block the position (x,y) // i.e. mark current position as visited
if there is an open spot at (x,y-1) AND f(x,y-1)
return true
if there is an open spot at (x,y+1) AND f(x,y+1)
return true
if there is an open spot at (x-1,y) AND f(x-1,y)
return true
if there is an open spot at (x+1,y) AND f(x+1,y)
return true
return false
}
Suppose you had the labyrinth looking like:
"+" is where you start ([1][1])
"-" is your destination ([3][1])
"#" is a blocked region
===========
|#|#|#|#|#|
|#|+| |#|#|
|#|#| |#|#|
|#|-| | |#|
|#|#|#|#|#|
===========
Using the above idea I have:
#include <stdio.h>
#define width 5
#define height 5
// print maze
void print(char arr[][width]){
for (int i = 0; i < 2*width+1; i++) printf("=");
printf("\n");
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
printf("|%c",arr[i][j]);
}
printf("|\n");
}
for (int i = 0; i < 2*width+1; i++) printf("=");
}
// starting from (x,y) to (destX,destY)
int path(int arr[][width],int x,int y,int destX,int destY,char toDest[][width]){
if (x==destX && y==destY) {
toDest[y][x] = '*';
print(toDest);
return 1;
}
// mark current position as visited
arr[y][x] = 0;
toDest[y][x] = '*';
// left
if (arr[y][x-1] && path(arr,x-1,y,destX,destY,toDest))
return 1;
// right
if (arr[y][x+1] && path(arr,x+1,y,destX,destY,toDest))
return 1;
// up
if (arr[y-1][x] && path(arr,x,y-1,destX,destY,toDest))
return 1;
// down
if (arr[y+1][x] && path(arr,x,y+1,destX,destY,toDest))
return 1;
return 0;
}
int main () {
// use this to store path
// and then print it out if found
char toDest[height][width] = {
{'#','#','#','#','#'},
{'#',' ',' ','#','#'},
{'#','#',' ','#','#'},
{'#',' ',' ',' ','#'},
{'#','#','#','#','#'}
};
// 0 -> position is blocked
// 1 -> position is open
int maze[height][width] = {
{0,0,0,0,0},
{0,1,1,0,0},
{0,0,1,0,0},
{0,1,1,1,0},
{0,0,0,0,0}
};
path(maze,1,1,1,3,toDest);
}
Output:
===========
|#|#|#|#|#|
|#|*|*|#|#|
|#|#|*|#|#|
|#|*|*| |#|
|#|#|#|#|#|
===========
In output the path is designated by the *s

error : expected identifier or '(' in global variable

I got this errror during compile processing.
I already saw this error in this site before, I think this error can occur when the ; or something are in wrong place. but I can't find.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#define MAX 80
typedef struct assemble
{
int op;
int ni;
int xbpe;
int addr;
}Assemble;
void get_token(char *bp);
int hTod(char *dp);
int bTod(char *dp);
void codeBreak(char *cp);
void result(int t);
Assemble asm;
int type;
int main()
{
FILE *fp;
char buf[MAX];
if( (fp = fopen("inst.txt","r")) == NULL ){
fprintf(stderr, "file not found...\n"); exit(1);
}
while(fgets(buf,sizeof(buf),fp) != NULL){
get_token(buf);
}
fclose(fp);
return 0;
}
void get_token(char *bp)
{
char *cp;
int i = 1;
for(cp=strtok(bp, " \t\n"); cp != NULL; )
{
if( (*(cp+0) == '0') && (*(cp+1) == 'x') )
{
if( i == -1 )
asm.addr = hTod(cp);
if( i == 1)
asm.op = hTod(cp);
i *= -1;
}
else
{
codeBreak(cp);
}
cp = strtok(NULL, " \t\n");
}
result(type);
}
void codeBreak(char *cp)
{
if ( strlen(cp) == 2 ) // ni 판단
{
asm.ni = bTod(cp);
}
else if( strlen(cp) == 1 )
{
asm.xbpe = bTod(cp)*pow(2,3);
type = 1;
}
else if( strlen(cp) == 4 )
{
if( *(cp+3) == '1')
{
asm.xbpe = bTod(cp);
type = 2;
}
else
{
asm.xbpe = bTod(cp);
type = 3;
}
}
}
void result(int t)
{
switch(t)
{
case 1 : printf("0x%x%x\n", (asm.op+asm.ni), asm.addr); break;
case 2 : printf("0x%x%x%.5x\n", (asm.op+asm.ni), asm.xbpe, asm.addr); break;
case 3 : printf("0x%x%x%.3x\n", (asm.op+asm.ni), asm.xbpe, asm.addr); break;
default : break;
}
}
/* Hex to decimal */
int hTod(char *dp)
{
int i;
int dec = 0;
for( i=2 ; i < strlen(dp) ; i++)
{
switch (*(dp+i))
{
case 'a' : *(dp+i) = 58; break;
case 'b' : *(dp+i) = 59; break;
case 'c' : *(dp+i) = 60; break;
case 'd' : *(dp+i) = 61; break;
case 'e' : *(dp+i) = 62; break;
case 'f' : *(dp+i) = 63; break;
}
dec += (*(dp+i)-48) * pow( 16, (strlen(dp)-(i+1)));
}
return dec;
}
/* binary to decimal*/
int bTod(char *dp)
{
int i;
int dec = 0;
for( i = 0; i < strlen(dp) ; i++)
{
dec += (*(dp+i)-48) * pow( 2, (strlen(dp) - (i+1)));
}
return dec;
}
asm is a keyword. Instead of
Assemble asm;
use something different, such as:
Assemble asm1;
The problem reported by the compiler is different though. You seem to have used
ASSEMBLY asm;
in the code you compiled.

Resources