error : expected identifier or '(' in global variable - c

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.

Related

No output from the program

In our student class we are building a small program to process the data from Oil & Gas Industry. The program at a rough condition, but we learn a lot through the project.
The program is compiled this way
In the below sections you can find the whole code of the source files. Here is the compilation routine:
gcc -fPIC -c parser.c -o parser.o
gcc -shared parser.c -o parser.dll
gcc -c well.c - o well.o
gcc -c main.c -o main.o
gcc main.o well.o -L. -lparser -o well.exe
Then we execute it this way: well.exe "WELL_DATA.csv" "NUM OF WELL TO FIND" >> well.log
The problem the execution starts, but the output from fprintf appears just sometimes, but usually not... We hope you can help us resolve our problem
main.c file content
#include"well.h"
FILE* input;
struct WELL* head = NULL; //the head of the list
struct TNode* tree = NULL;
int main(int argc, char *argv[3]) {
CBUFFER* buffer = malloc(sizeof(CBUFFER));
buffer->len = BUFFER_SIZE;
input = fopen(argv[1], "r");
struct WELL* instance = NULL;
while(buffer->len != 0){
flushBuffer(buffer);
getNextLine(input, buffer);
if (buffer->len == 0)
break;
parseData(buffer);
instance = createWell(buffer);
addWell(instance, &head);
}
instance = getWell(argv[2], head);
if (instance != NULL)
fprintf(stdout,"NAME = %s\tLIFT_TYPE = %i\tMONTHLY_OIL_FLOW_RATE = %.2f\n", instance->name, instance->prodMethod, instance->oil.monthly);
else fprintf(stdout,"No such well\n");
freeList(head);
fclose(input);
return 0;
}
In the following sections you can find the rest of the code. Here is the parser.c which processes the data:
#include "parser.h"
unsigned short getNextLine(FILE* input, CBUFFER* buffer){
//printf("Getting next line\n");
unsigned short len = 0;
char symbol = fgetc(input);
if (!input || !buffer)
return 0;
while ((symbol != '\n' && (symbol != EOF))){
//
*((buffer->data) + len) = symbol;
symbol = fgetc(input);
len++;
}
*((buffer->data) + len) = '\n';
buffer->len = len;
buffer->index = 0;
return buffer->len;
}
unsigned short parseData(CBUFFER* buffer){
char *temp = malloc(sizeof(char) * (buffer->len + 1));
unsigned short i = 0;
unsigned short j = 0;
while (*((buffer->data) + i) != '\n'){
if (*((buffer->data) + i) == '\0' || *((buffer->data) + i) == '\r' || *((buffer->data) + i) == '\v' ||
*((buffer->data) + i) == '\t' || *((buffer->data) + i) == '\f')
i++;
else{
if (*((buffer->data) + i) == ';')
*(temp + j) = '\0';
else
*(temp + j) = *((buffer->data) + i);
j++;
}
i++;
}
*(temp + j) = '\n';
flushBuffer(buffer);
i = 0;
while (*(temp + i) != '\n'){
*((buffer->data) + i) = *(temp + i);
i++;
}
*((buffer->data) + i) = '\0';
free(temp);
buffer->len = i;
return buffer->len;
}
char* getValue(CBUFFER* buffer)
{
int i = buffer->index;
int j = buffer->index;
char c;
for (; i <= buffer->len; i++)
{
c = buffer->data[i];
if (c == '\0')
{
char* newValue = (char*)malloc(sizeof(char) * (i - buffer->index + 1));
for (; j <= i ; j++)
{
newValue[j - buffer->index] = buffer->data[j];
}
newValue[j - buffer->index] = '\0';
buffer->index = i + 1;
return newValue;
}
}
return NULL;
}
DATE getDate(char* input, char delimeter){
DATE date;
unsigned short number = 0;
char c = input[0];
for(unsigned short i = 1, j = 0; i < 12; i++){
number = number * 10 + atoi(&c);
c = input[i];
if((c == delimeter) || (c == '\0')){
if (j == 0) date.day = number;
if (j == 1) date.month = number;
if (j == 2){
date.year = number;
break;
}
number = 0;
j++;
}
}
return date;
}
int flushBuffer(CBUFFER* buffer) {
unsigned short i = 0;
while( i < buffer->len){
*((buffer->data)+i) = '\0';
i++;
}
buffer->len = 0;
return 0;
}
And the part which defines the well-object we work with well.c:
#include "well.h"
struct WELL* createWell(CBUFFER* pbuffer) {
struct WELL* instance = malloc(sizeof(struct WELL));
char * nextValue = getValue(pbuffer);
unsigned i = 0;
while ( nextValue != NULL){
setProperty(instance, i, nextValue);
i++;
nextValue = getValue(pbuffer);
}
instance->next = NULL;
return instance;
}
unsigned setProperty(struct WELL* instance, unsigned prop_index, char* value) {
switch(prop_index){
case 0:
setWellName(instance, value);
break;
case 1:
setWellDate(instance, getDate(value, '/'));
break;
case 2:
setProductionMethod(instance, value);
break;
case 3:
setFormation(instance, value);
break;
case 4:
setPump(instance, value);
break;
case 5:
setProduction(instance, OIL, MONTH, atof(value));
break;
case 6:
setProduction(instance, OIL, YEAR, atof(value));
break;
case 7:
setProduction(instance, OIL, COMMULATIVE, atof(value));
break;
case 8:
setProduction(instance, WATER, MONTH, atof(value));
break;
case 9:
setProduction(instance, WATER, YEAR, atof(value));
break;
case 10:
setProduction(instance, WATER, COMMULATIVE, atof(value));
break;
// PAY ATTENTION THAT cases from 11 to 13 are skipped!
// THIS IS BECAUSE WE DON'T NEED m3 PARAMETERS as it is
// AND CAN CALCULATE THEM from tons using density parameter
case 14:
setProduction(instance, MIX, MONTH, atof(value));
break;
case 15:
setProduction(instance, MIX, YEAR, atof(value));
break;
case 16:
setProduction(instance, MIX, COMMULATIVE, atof(value));
break;
case 17:
setProduction(instance, MIX, MONTH, atof(value));
break;
case 18:
setProduction(instance, MIX, YEAR, atof(value));
break;
case 19:
setProduction(instance, MIX, COMMULATIVE, atof(value));
break;
}
return 0;
}
unsigned addWell(struct WELL* instance, struct WELL** head) {
if (*head == NULL) {
*head = instance;
} else {
struct WELL* tmp = *head;
while (tmp->next){
tmp = tmp->next;
}
tmp->next = instance;
}
return 0;
}
struct WELL* getWell(char* key, struct WELL* head) {
if (head == NULL) return NULL;
struct WELL* currentWell = head;
while (strcmp(currentWell->name, key) != 0) {
if (currentWell->next == NULL) return NULL;
currentWell = currentWell->next;
}
return currentWell;
}
char* setWellName(struct WELL* instance, char* value) {
strcpy(instance->name, value);
return instance->name;
}
char* setFormation(struct WELL* instance, char* value) {
strcpy(instance->devFormation, value);
return instance->devFormation;
}
char* setPump(struct WELL* instance, char* value) {
strcpy(instance->pump, value);
return instance->pump;
}
DATE setWellDate(struct WELL* instance, DATE date) {
instance->startDate.day = date.day;
instance->startDate.month = date.month;
instance->startDate.year = date.year;
return instance->startDate;
}
WLIFT_TYPE setProductionMethod(struct WELL* instance, char* value) {
if (!strcmp(value, "flush"))
instance->prodMethod = FLUSH;
if (!strcmp(value, "gaslift"))
instance->prodMethod = GAS_LIFT;
if (!strcmp(value, "pump"))
instance->prodMethod = PUMP;
return instance->prodMethod;
}
double setProduction(struct WELL* instance, WFLUID fluid, WPERIOD period , double value) {
if (fluid == OIL) {
if (period == MONTH) {
instance->oil.monthly = value;
return instance->oil.monthly;
} else if (period == YEAR) {
instance->oil.year = value;
return instance->oil.year;
} else if (period == COMMULATIVE) {
instance->oil.commulative = value;
return instance->oil.commulative;
}
} else if (fluid == GAS) {
if (period == MONTH) {
instance->gas.monthly = value;
return instance->gas.monthly;
} else if (period == YEAR) {
instance->gas.year = value;
return instance->gas.year;
} else if (period == COMMULATIVE) {
instance->gas.commulative = value;
return instance->gas.commulative;
}
} else if (fluid == WATER) {
if (period == MONTH) {
instance->water.monthly = value;
return instance->water.monthly;
} else if (period == YEAR) {
instance->water.year = value;
return instance->water.year;
} else if (period == COMMULATIVE) {
instance->water.commulative = value;
return instance->water.commulative;
}
} else if (fluid == MIX) {
if (period == MONTH) {
instance->liquid.monthly = value;
return instance->liquid.monthly;
} else if (period == YEAR) {
instance->liquid.year = value;
return instance->liquid.year;
} else if (period == COMMULATIVE) {
instance->liquid.commulative = value;
return instance->liquid.commulative;
}
}
}

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;
}

Printing string pointers in c

So, essentially I have two files:
File 1:
//
// main.c
// frederickterry
//
// Created by Rick Terry on 1/15/15.
// Copyright (c) 2015 Rick Terry. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int size (char *g) {
int ofs = 0;
while (*(g+ofs) != '\0') {
++ofs;
}
return ofs;
}
int parse(char *g) {
// Setup
char binaryConnective;
int negated = 0;
// Looking for propositions
int fmlaLength = size(g);
if(fmlaLength == 0) {
return 1;
}
if(fmlaLength == 1) {
if(g[0] == 'p') {
return 1;
} else if (g[0] == 'q') {
return 1;
} else if (g[0] == 'r') {
return 1;
} else {
return 0;
}
}
// Now looking for negated preposition
if(fmlaLength == 2) {
char temp[100];
strcpy(temp, g);
if(g[0] == '-') {
negated = 1;
int negatedprop = parse(g+1);
if(negatedprop == 1) {
return 2;
}
}
}
// Checking if Binary Formula
char arrayleft[50];
char arrayright[50];
char *left = "";
char *right = "";
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int binarypresent = 0;
if(fmlaLength != 1 && fmlaLength != 2) {
if(g[0] == '-') {
int negatedBinary = parse(g+1);
if(negatedBinary == 1 || negatedBinary == 2 || negatedBinary == 3) {
return 2;
} else {
return 0;
}
}
int i = 0;
int l = 0;
int p = strlen(g);
for(l = 0; l < strlen(g)/2; l++) {
if(g[l] == '(' && g[p-l-1] == ')') {
i++;
}
}
for(int q = i; q < strlen(g); q++) {
if(g[q] == '(') {
numLeft++;
} else if(g[q] == ')') {
numRight++;
}
arrayleft[q] = g[q];
//printf("%c", arrayleft[i]);
//printf("%s", left);
if((numRight == numLeft) && (g[q+1] == 'v' || g[q+1] == '>' || g[q+1] == '^')) {
arrayleft[q+1] = '\0';
bclocation = q+1;
binaryConnective = g[q+1];
binarypresent = 1;
// printf("The binary connecive is: %c\n", binaryConnective);
break;
}
}
if(binarypresent == 0) {
return 0;
}
int j = 0;
for(int i = bclocation+1; i < strlen(g)-1; i++) {
arrayright[j] = g[i];
j++;
}
arrayright[j] = '\0';
left = &arrayleft[1];
right = &arrayright[0];
//printf("Printed a second time, fmla 1 is: %s", left);
int parseleft = parse(left);
// printf("Parse left result: %d\n", parseleft);
if(parseleft == 0) {
return 0;
}
int parseright = parse(right);
if(parseright == 0) {
return 0;
}
// printf("Parse right result: %d\n", parseleft);
if(negated == 1) {
return 2;
} else {
return 3;
}
}
return 0;
}
int type(char *g) {
if(parse(g) == 1 ||parse(g) == 2 || parse(g) == 3) {
if(parse(g) == 1) {
return 1;
}
/* Literals, Positive and Negative */
if(parse(g) == 2 && size(g) == 2) {
return 1;
}
/* Double Negations */
if(g[0] == '-' && g[1] == '-') {
return 4;
}
/* Alpha & Beta Formulas */
char binaryConnective;
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int binarypresent = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
bclocation = i+1;
binaryConnective = g[i+1];
binarypresent = 1;
break;
}
}
}
/* Connective established */
if(binaryConnective == '^') {
if(g[0] == '-') {
return 3;
} else {
return 2;
}
} else if(binaryConnective == '>') {
if(g[0] == '-') {
return 2;
} else {
return 3;
}
} else if (binaryConnective == 'v') {
if(g[0] == '-') {
return 2;
} else {
return 3;
}
}
}
return 0;
}
char bin(char *g) {
char binaryConnective;
char arrayLeft[50];
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
int j = 0;
arrayLeft[j++] = g[i];
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
arrayLeft[i+1] = '\0';
bclocation = i+1;
binaryConnective = g[i+1];
return binaryConnective;
}
}
}
return binaryConnective;
}
char *partone(char *g) {
char binaryConnective;
char arrayLeft[50];
char arrayRight[50];
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
int j = 0;
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
arrayLeft[j] = g[i];
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
arrayLeft[j+1] = '\0';
bclocation = i+1;
binaryConnective = g[i+1];
break;
}
}
j++;
}
int m = 0;
for(int k = bclocation+1; k < strlen(g)-1; k++) {
arrayRight[m] = g[k];
m++;
}
arrayRight[m] = '\0';
char* leftSide = &arrayLeft[0];
// printf("%s\n", leftSide);
// printf("%s\n", rightSide);
int k = 0;
k++;
return leftSide;
}
char *parttwo(char *g) {
char binaryConnective;
char arrayLeft[50];
char arrayRight[50];
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
int j = 0;
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
arrayLeft[j] = g[i];
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
arrayLeft[j+1] = '\0';
bclocation = i+1;
binaryConnective = g[i+1];
break;
}
}
j++;
}
int m = 0;
int n = size(g) - 1;
if(g[strlen(g)-1] != ')') {
n++;
}
for(int k = bclocation+1; k < n; k++) {
arrayRight[m] = g[k];
m++;
}
arrayRight[m] = '\0';
char* leftSide = &arrayLeft[0];
char* rightSide = &arrayRight[0];
// printf("%s\n", leftSide);
// printf("%s\n", rightSide);
return rightSide;
}
char *firstexp(char *g) {
char* left = partone(g);
char leftArray[50];
int i = 0;
for(i; i < strlen(left); i++) {
leftArray[i] = left[i];
}
leftArray[i] = '\0';
char binConnective = bin(g);
int typeG = type(g);
if(typeG == 2) {
if(binConnective == '^') {
return &leftArray;
} else if(binConnective == '>') {
return &leftArray;
}
} else if(typeG == 3) {
if(binConnective == 'v')
return &leftArray;
}
char temp[50];
for(int i = 0; i < strlen(leftArray); i++) {
temp[i+1] = leftArray[i];
}
temp[0] = '-';
char* lefttwo = &temp[0];
if(typeG == 2) {
if(binConnective == 'v') {
return lefttwo;
}
} else if(typeG == 3) {
if(binConnective == '>' || binConnective == '^') {
return lefttwo;
}
}
return "Hello";
}
char *secondexp(char *g) {
// char binaryConnective = bin(g);
// char* right = parttwo(g);
// char rightArray[50];
// int i = 0;
// for(i; i< strlen(right); i++) {
// rightArray[i+1] = right[i];
// }
// rightArray[i] = '\0';
// int typeG = type(g);
// if(type(g) == 2) {
// if(binaryConnective == '^') {
// return &rightArray;
// }
// } else if(type(g) == 3) {
// if(binaryConnective == 'v' || binaryConnective == '>') {
// return &rightArray;
// }
// }
return "Hello";
}
typedef struct tableau tableau;
\
\
struct tableau {
char *root;
tableau *left;
tableau *right;
tableau *parent;
int closedbranch;
};
int closed(tableau *t) {
return 0;
}
void complete(tableau *t) {
}
/*int main(int argc, const char * argv[])
{
printf("Hello, World!\n");
printf("%d \n", parse("p^q"));
printf("%d \n", type("p^q"));
printf("%c \n", bin("p^q"));
printf("%s\n", partone("p^q"));
printf("%s\n", parttwo("p^q"));
printf("%s\n", firstexp("p^q"));
printf("Simulation complete");
return 0;
}*/
File 2:
#include <stdio.h>
#include <string.h> /* for all the new-fangled string functions */
#include <stdlib.h> /* malloc, free, rand */
#include "yourfile.h"
int Fsize = 50;
int main()
{ /*input a string and check if its a propositional formula */
char *name = malloc(Fsize);
printf("Enter a formula:");
scanf("%s", name);
int p=parse(name);
switch(p)
{case(0): printf("not a formula");break;
case(1): printf("a proposition");break;
case(2): printf("a negated formula");break;
case(3): printf("a binary formula");break;
default: printf("what the f***!");
}
printf("\n");
if (p==3)
{
printf("the first part is %s and the second part is %s", partone(name), parttwo(name));
printf(" the binary connective is %c \n", bin(name));
}
int t =type(name);
switch(t)
{case(0):printf("I told you, not a formula");break;
case(1): printf("A literal");break;
case(2): printf("An alpha formula, ");break;
case(3): printf("A beta formula, ");break;
case(4): printf("Double negation");break;
default: printf("SOmewthing's wrong");
}
if(t==2) printf("first expansion fmla is %s, second expansion fmla is %s\n", firstexp(name), secondexp(name));
if(t==3) printf("first expansion fmla is %s, second expansion fmla is %s\n", firstexp(name), secondexp(name));
tableau tab;
tab.root = name;
tab.left=0;
tab.parent=0;
tab.right=0;
tab.closedbranch=0;
complete(&tab);/*expand the root node then recursively expand any child nodes */
if (closed(&tab)) printf("%s is not satisfiable", name);
else printf("%s is satisfiable", name);
return(0);
}
If you look at the first file, you'll see a method called * firstexp(char * g).
This method runs perfectly, but only if another method called * secondexp(char * g) is commented out.
If * secondexp(char * g) is commented out, then *firstexp runs like this:
Enter a formula:((pvq)>-p)
a binary formula
the first part is (pvq) and the second part is -p the binary connective is >
A beta formula, first expansion fmla is -(pvq), second expansion fmla is Hello
((pvq)>-p) is satisfiableProgram ended with exit code: 0
otherwise, if *secondexp is not commented out, it runs like this:
Enter a formula:((pvq)>-p)
a binary formula
the first part is (pvq) and the second part is -p the binary connective is >
A beta formula, first expansion fmla is \240L, second expansion fmla is (-
((pvq)>-p) is satisfiable. Program ended with exit code: 0
As you can see, the outputs are completely different despite the same input. Can someone explain what's going on here?
In the commented-out parts of secondexp and in parttwo, you return the address of a local variable, which you shouldn't do.
You seem to fill a lot of ad-hoc sized auxiliary arrays. These have the problem that they might overflow for larger expressions and also that you cannot return them unless you allocate them on the heap with malloc, which also means that you have to free them later.
At first glance, the strings you want to return are substrings or slices of the expression string. That means that the data for these strings is already there.
You could (safely) return pointers into that string. That is what, for example strchr and strstr do. If you are willing to modify the original string, you could also place null terminators '\0' after substrings. That's what strtok does, and it has the disadvantage that you lose the information at that place: If you string is a*b and you modify it to a\0b, you will not know which operator there was.
Another method is to create a struct that stores a slice as pointer into the string and a length:
struct slice {
const char *p;
int length;
};
You can then safely return slices of the original string without needing to worry about additional memory.
You can also use the standard functions in most cases, if you stick to the strn variants. When you print a slice, you can do so by specifying a field width in printf formats:
printf("Second part: '%.*s'\n", s->length, s->p);
In your parttwo() function you return the address of a local variable
return rightSide;
where rightSide is a pointer to a local variable.
It appears that your compiler gave you a warning about this which you solved by making a pointer to the local variabe arrayRight, that may confuse the compiler but the result will be the same, the data in arrayRight will no longer exist after the function returns.
You are doing the same all over your code, and even worse, in the secondexp() function you return a the address of a local variable taking it's address, you are not only returning the address to a local variabel, but also with a type that is not compatible with the return type of the function.
This is one of many probable issues that your code may have, but you need to start fixing that to continue with other possible problems.
Note: enable extra warnings when compiler and listen to them, don't try to fool the compiler unless you know exactly what you're doing.

RPN with header, Why doesn't it work?

I did a RPN, but doesn't show the result and the steps, before was appearing, I don't understand what is happening and there are no errors thrown by compiler either.
I do always this example:
3.2 1.8 - 10 / 2 + .
4 steps
= 2.14
I really don't know what's wrong ...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <ctype.h>
// quando dá enter ele fecha
// não está imprimindo o resultado O__O
typedef double pilha_t;
#define PILHA_VAZIA INT_MIN
#define N 100
#define TRUE 1
#define FALSE 0
struct Pilha {
pilha_t pilha[N];
int tamanho;
};
void inicializar(struct Pilha *p) {
p->tamanho = 0;
}
int cheia(struct Pilha *p) {
if (p->tamanho == N)
return TRUE;
return FALSE;
}
int vazia(struct Pilha *p) {
if (p->tamanho == 0)
return TRUE;
return FALSE;
}
void empilhar(struct Pilha *p, pilha_t num) {
if (cheia(p))
printf("Atencao: Pilha cheia!\n");
else {
p->pilha[p->tamanho] = num;
p->tamanho++;
}
}
pilha_t desempilhar(struct Pilha *p) {
if (vazia(p)) {
printf("Atencao: Pilha vazia!\n");
return PILHA_VAZIA;
}
else {
p->tamanho--;
return p->pilha[p->tamanho];
}
}
void imprimir(struct Pilha *p) {
int i;
printf("Pilha");
for(i=0; i < p->tamanho; i++)
printf(" %lf", p->pilha[i]);
printf("\n");
}
int main(int argc, char **argv)
{
struct Pilha p;
char str[30];// nao esta sendo usada,msg amarela
inicializar (&p);
char ch1[30];
printf("Digite a expressao: ");
fgets(ch1, 30, stdin);
int i, linha;
char s[30];
int k;
for(k=0;k<30;k++)
s[k]=' ';
for (i=0; i<30; i++) {
char C = ch1[i];
//printf(" %c \n", C);
if (isdigit(C) || C == '.'){
s[linha++] = C;
} else if (s[0] == '.') {
double total;
total = desempilhar(&p);
printf( "Total = %.2lf\n", total);
break;
}
else if (C == ' ') {
if (atof(s) != 0)
empilhar(&p, atof(s));
linha = 0;
int k;
for(k=0;k<30;k++)
s[k]=' ';
}
else if ((C == '+') || (C == '-') || (C == '*') || (C == '/')) {
double n1, n2, total;
n2 = desempilhar(&p);
n1 = desempilhar(&p);
switch (ch1[i]) {
case '+': total = n1 + n2; break;
case '-': total = n1 - n2; break;
case '*': total = n1 * n2; break;
case '/': total = n1 / n2; break;
default : printf( "erro no operador\n");
exit( EXIT_FAILURE);
}
empilhar(&p, total);
}
else
break;
}
return (0);
}
The line int i, linha; should be :
int i, linha = 0;
EDIT :
As you never use imprimir in your code, steps could not appear. I make some slight modifications in your code apart from the fix above :
add a #define DEBUG 1 near the beginning of program to control trace prints
protect the #define DEBUG 1 with a #ifndef block to allow to define it at compilation time
reverse the order of imprimir and empilhar to allow the use of imprimir in the body of empilhar
add a call to imprimir in empilhar
Here is the resulting code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <ctype.h>
// quando dá enter ele fecha
// não está imprimindo o resultado O__O
typedef double pilha_t;
#define PILHA_VAZIA INT_MIN
#define N 100
#define TRUE 1
#define FALSE 0
#ifndef DEBUG
#define DEBUG 1
#endif
struct Pilha {
pilha_t pilha[N];
int tamanho;
};
void inicializar(struct Pilha *p) {
p->tamanho = 0;
}
int cheia(struct Pilha *p) {
if (p->tamanho == N)
return TRUE;
return FALSE;
}
int vazia(struct Pilha *p) {
if (p->tamanho == 0)
return TRUE;
return FALSE;
}
pilha_t desempilhar(struct Pilha *p) {
if (vazia(p)) {
printf("Atencao: Pilha vazia!\n");
return PILHA_VAZIA;
}
else {
p->tamanho--;
return p->pilha[p->tamanho];
}
}
void imprimir(struct Pilha *p) {
int i;
printf("Pilha");
for(i=0; i < p->tamanho; i++)
printf(" %lf", p->pilha[i]);
printf("\n");
}
void empilhar(struct Pilha *p, pilha_t num) {
if (cheia(p))
printf("Atencao: Pilha cheia!\n");
else {
p->pilha[p->tamanho] = num;
p->tamanho++;
if (DEBUG) {
imprimir(p);
}
}
}
int main(int argc, char **argv)
{
struct Pilha p;
char str[30];// nao esta sendo usada,msg amarela
inicializar (&p);
char ch1[30];
printf("Digite a expressao: ");
fgets(ch1, 30, stdin);
int i, linha = 0;
char s[30];
int k;
for(k=0;k<30;k++)
s[k]=' ';
for (i=0; i<30; i++) {
char C = ch1[i];
//printf(" %c \n", C);
if (isdigit(C) || C == '.'){
s[linha++] = C;
} else if (s[0] == '.') {
double total;
total = desempilhar(&p);
printf( "Total = %.2lf\n", total);
break;
}
else if (C == ' ') {
if (atof(s) != 0)
empilhar(&p, atof(s));
linha = 0;
int k;
for(k=0;k<30;k++)
s[k]=' ';
}
else if ((C == '+') || (C == '-') || (C == '*') || (C == '/')) {
double n1, n2, total;
n2 = desempilhar(&p);
n1 = desempilhar(&p);
switch (ch1[i]) {
case '+': total = n1 + n2; break;
case '-': total = n1 - n2; break;
case '*': total = n1 * n2; break;
case '/': total = n1 / n2; break;
default : printf( "erro no operador\n");
exit( EXIT_FAILURE);
}
empilhar(&p, total);
}
else
break;
}
return (0);
}
Here is an example of use :
Digite a expressao: 3.2 1.8 - 10 / 2 + .
Pilha 3.200000
Pilha 3.200000 1.800000
Pilha 1.400000
Pilha 1.400000 10.000000
Pilha 0.140000
Pilha 0.140000 2.000000
Pilha 2.140000
Total = 2.14

C - segmentation fault on long running while loop

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.

Resources