: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am running the programm , which includes reading Hard disk drive ID and ethernet mac ID also Advanced encryption std is used .
when i compile the program with command line "gcc -Wall securiti.c -lcrypto" getting the compilation error.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/hdreg.h>
#include <net/if.h>
#include <unistd.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/ioctl.h>
#include <openssl/aes.h>
#include <openssl/rand.h>
unsigned char aes(char **argv)
unsigned char* hddid(char *devname);
unsigned char* macid(void);
//unsigned char* xor1(char hdd_id,char mac_id);
unsigned char* char1();
unsigned char* xor(char c,char d);
char destroy(char* argv[]);
int main(int argc, char *argv[])
{
unsigned char *hdd_id;
unsigned char *mac_id;
unsigned char c;
unsigned char d;
unsigned char e;
unsigned char c1;
//unsigned char c2;
unsigned char h;
unsigned char m;
int i,s;
char f;
//remove(argv[0]);
if (geteuid() > 0)
{
printf("ERROR: Must be root to use\n");
exit(1);
}
hdd_id = hddid(argv[1]);
h = hdd_id;
mac_id = macid();
m = mac_id;
printf("\nHard disk Serial Number A:%.20s\n", hdd_id);
printf("\nMac Id B: ");
for(i = 0; i < 6; i++)
printf("%x ", mac_id[i]);
printf("\n");
int j; /*
c = xor1(hdd_id,mac_id);
printf("\nxor of two id's C=%x\n");*/
//for(j = 0;j < 6;j++)
//printf("%x",c[j]);
c = aes(argv[1]);
printf("\n%s",aes);
//printf("\nxor of two ids c=%x\n");
printf("======================");
d = char1();
printf("\nThe value of D=%x\n",d);
printf("--------------------------");
e = xor(c,d);
printf("\nxor of C and D is E=%x\n",e);
printf("----------------------------");
FILE* fp;
fp = fopen("/tmp/mymo.lic", "w");
if (fp == NULL)
{
printf("unable to write into a file.\n");
exit(0);
}
fprintf(fp,"%c",e);
c1 = e-d;
printf("\nvlaue of c1=%x\n",c1);
printf("*****************************");
/* c2 = h + m;
printf("\nvalue of c2=%x\n",c2);
*/
if(c1!=c)
{
printf("\nThe security key is valid\n");
}
else
{
printf("\nThe security key is valid\n");
printf("*****************************\n");
}
printf("*****************************\n");
/*int r;
if(r<=2)
{
printf("Do not run the program more than two times,");
else
remove(argv[0]);
}
//s = destroy(argv[0]);
exit(0);*/
remove(argv[0]);
return 0;
}
char destroy( char *argv[0])
{
int s;
char file_name[10];
printf("Enter the file_name:");
gets(file_name);
s = remove(file_name);
if(s==0)
printf("%s\n",file_name);
return unlink(argv[0]);
remove(argv[0]);
}
//xor function
unsigned char* xor(char c,char d)
{
char z;
z = c^d;
//printf("%x\n",z);
return z;
}
//char1 function
unsigned char* char1()
{
char str[10];
int i=0;
printf("\nEnter a string: ");
scanf("%s",str);
//printf("%s",str[i]);
printf("\nASCII values of given string is D:",str);
while(str[i])
{
printf("%d",str[i++]);
printf("\n");
}
return str;
}
//xor function
/* unsigned char* xor1(char hdd_id,char mac_id)
{
char y;
y = hdd_id ^ mac_id;
//printf("xor c :%x\n",y);
return y;
}*/
//hddid function
unsigned char* hddid(char *devname)
{
static struct hd_driveid hd;
int fd;
if ((fd = open(devname, O_RDONLY|O_NONBLOCK)) < 0)
{
printf("ERROR: Cannot open device %s\n", devname);
exit(1);
}
if (ioctl(fd, HDIO_GET_IDENTITY, &hd))
{
perror("ERROR: HDIO_GET_IDENTITY");
exit(1);
}
return hd.serial_no;
}
unsigned char* macid(void)
{
struct ifreq ifr;
struct ifconf ifc;
char buf[1024];
int success = 0;
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
if (sock == -1)
{
perror("sock:");
}
ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = buf;
if (ioctl(sock, SIOCGIFCONF, &ifc) == -1)
{
perror("ioctl:");
}
struct ifreq* it = ifc.ifc_req;
const struct ifreq* const end = it + (ifc.ifc_len / sizeof(struct ifreq));
for (it; it != end; ++it) {
strcpy(ifr.ifr_name, it->ifr_name);
if (ioctl(sock, SIOCGIFFLAGS, &ifr) == 0) {
if (! (ifr.ifr_flags & IFF_LOOPBACK)) { // don't count loopback
if (ioctl(sock, SIOCGIFHWADDR, &ifr) == 0) {
success = 1;
break;
}
}
}
else {
perror("ioctl:");
}
}
static unsigned char mac_address[6];
int i;
if (success) memcpy(mac_address, ifr.ifr_hwaddr.sa_data, 6);
return mac_address;
}
unsigned char aes(char **argv)
{
int i;
int keylength;
printf("Give a key length [only 128 or 192 or 256]:\n");
scanf("%d", &keylength);
/* generate a key with a given length */
unsigned char aes_key[keylength];
memset(aes_key, 0, sizeof(aes_key));
if (!RAND_bytes(aes_key, keylength))
{
//printf("girish\n");
exit(-1);
}
aes_key[keylength-1] = '\0';
int inputslength;
printf("Give an input's length:\n");
scanf("%d", &inputslength);
/* generate input with a given length */
unsigned char aes_input[inputslength+1];
memset(aes_input, '0', sizeof(aes_input));
aes_input[inputslength] = '\0';
/*printf("original:\t");
for(i=0; i<inputslength; i++)
{
printf("%c ", aes_input[i]);
}
printf("\n");*/
/* init vector */
unsigned char iv[AES_BLOCK_SIZE];
if (!RAND_bytes(iv, AES_BLOCK_SIZE));
{
exit(-1);
}
//printf("AES_BLOCK_SIZE = %d\n", AES_BLOCK_SIZE);
// aes block size is 16 bytes = 128 bits
AES_KEY enc_key, dec_key;
unsigned char enc_out[AES_BLOCK_SIZE];
unsigned char dec_out[AES_BLOCK_SIZE];
// so i can do with this aes-cbc-128 aes-cbc-192 aes-cbc-256
AES_set_encrypt_key(aes_key, keylength, &enc_key);
AES_cbc_encrypt(aes_input, enc_out, inputslength, &enc_key, iv, AES_ENCRYPT);
printf("girish121\n");
AES_set_decrypt_key(aes_key, keylength, &dec_key);
printf("girish12\n");
AES_decrypt(enc_out, dec_out, &dec_key);
printf("original:\t");
for(i=0;*(aes_input+i)!=0x00;i++)
{
printf("%X ",*(aes_input+i));
//AES_set_decrypt_key(aes_key,keylength,&dec_key);
printf("\nencrypted:\t");
printf("\ng\n");
}
for(i=0;*(enc_out+i)!=0x00;i++)
{
printf("%X ",*(enc_out+i));
printf("\ng1\n");
printf("\ndecrypted:\t");
}
for(i=0;*(dec_out+i)!=0x00;i++)
{
printf("%X ",*(dec_out+i));
printf("\ng3");
printf("\n");
}
return 0;
}

Semicolon missing.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/hdreg.h>
#include <net/if.h>
#include <unistd.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/ioctl.h>
#include <openssl/aes.h>
#include <openssl/rand.h>
unsigned char aes(char **argv) //unsigned char aes(char **argv);

Related

Message queues: Bad file descriptor in notification

I've created a table of mq file descriptors and I'm trying to pass numbers from stdin by one of them.
I'm using notification using threads and when a number occures in one of the queues it should print for example "Number: 1 from queue: 3".
Here's my code:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <time.h>
#include <mqueue.h>
#define MAX_LENGTH 20
#define ERR(source) (\
fprintf(stderr, "%s:%d\n", __FILE__, __LINE__),\
perror(source),\
kill(0, SIGKILL),\
exit(EXIT_FAILURE)\
)
static void not_func(union sigval sv) {
mqd_t queue;
uint8_t number;
unsigned msg_prio;
queue = *((mqd_t*)sv.sival_ptr);
static struct sigevent not;
not.sigev_notify = SIGEV_THREAD;
not.sigev_notify_function = not_func;
not.sigev_value.sival_ptr = &queue;
if(mq_notify(queue, &not)<0) ERR("mq_notify");
for(;;) {
if(mq_receive(queue, (char*)&number, 1, &msg_prio)<1) {
if(errno == EAGAIN) break;
else ERR("mq_receive");
printf("Number: %d from queue: %d", number, msg_prio);
}
}
}
void get_queue_name(int nr, char *str) {
snprintf(str, MAX_LENGTH, "/queue%d", nr);
}
mqd_t create_message_queue(int nr) {
mqd_t queue;
char name[MAX_LENGTH] = "";
get_queue_name(nr, name);
struct mq_attr attr;
attr.mq_maxmsg = 10;
attr.mq_msgsize = 1;
if((queue = TEMP_FAILURE_RETRY(mq_open(name, O_RDWR|O_NONBLOCK|O_CREAT, 0600, &attr))) == (mqd_t)-1) ERR("mq open in");
static struct sigevent not;
not.sigev_notify = SIGEV_THREAD;
not.sigev_notify_function = not_func;
not.sigev_value.sival_ptr = &queue;
if(mq_notify(queue, &not)<0) ERR("mq_notify");
return queue;
}
void delete_message_queue(mqd_t queue, int nr) {
char name[MAX_LENGTH] = "";
get_queue_name(nr, name);
mq_close(queue);
if(mq_unlink(name)) ERR("mq_unlink");
}
void usage(void) {
fprintf(stderr, "USAGE: mqueue n\n");
fprintf(stderr, "100 > n > 0 - number of children\n");
exit(EXIT_FAILURE);
}
int main(int argc, char **argv) {
int n, i;
char strnumber[MAX_LENGTH];
int number;
mqd_t *queues;
srand(time(NULL));
if(argc != 2) usage();
n = atoi(argv[1]);
if(n<=0 || n>=100) usage();
queues = (mqd_t*)malloc(sizeof(mqd_t) * n);
if(queues == NULL) ERR("malloc");
for(i = 0; i < n; i++) {
queues[i] = create_message_queue(i+1);
}
while(fgets(strnumber, MAX_LENGTH, stdin)!=NULL) {
number = (uint8_t)atoi(strnumber);
if(number<=0) continue;
int randomQueue = rand()%n;
if(TEMP_FAILURE_RETRY(mq_send(queues[randomQueue], (const char *)&number, 1, (unsigned)randomQueue))) ERR("mq_send");
}
for(i = 0; i < n; i++) {
delete_message_queue(queues[i], i+1);
}
free(queues);
return EXIT_SUCCESS;
}
When I execute my code nothing happens:
or I have such an error:
You pass a pointer to queue (which is a local variable) to the thread (via not.sigev_value.sival_ptr) which runs after that variable goes out of scope. So it gets a dangling pointer.
Either pass the descriptor by value (if it fits in sigval; it should), or store it on the heap (with new/malloc) and pass that pointer.

Issues printing a MAC address

A MAC address is parsed into an array of bytes (macaddr). The bytes are
printed with printf() one after another. The bytes are supposed to look as
pairs of hexadecimal characters. But some of them are padded with f
characters.
For example, for macaddr[3] it prints 'ffffffcc' rather than 'cc', i.e.
4 bytes instead of single byte. The rest of the array items are printed
correctly (macaddr[0] = 00, macaddr[1] = AA, macaddr[2] = BB,
etc.)
What's the problem?
Please help me to figure out what's wrong with the program.
#include <stdio.h>
#include <net/if.h> // struct ifconf
#include <errno.h>
#include <libnet.h>
#include <pcap.h>
#include <stdlib.h>
#include <unistd.h>
int getmacaddr() ;
int main(int argc, char *argv[])
{
getmacaddr();
}
int getmacaddr()
{
struct ifconf ifc;
struct ifreq *ifr;
int sfd;
int i;
int devnums;
char macaddr[ETHER_ADDR_LEN];
ifc.ifc_req = NULL;
sfd = socket(AF_INET,SOCK_DGRAM,0);
if(sfd == -1)
{
perror("socket : ");
return -1;
}
// get ifc.ifc_len
if(ioctl(sfd,SIOCGIFCONF,&ifc) == -1)
{
perror("ioctl - SIOCGIFCONF : ");
return -1;
}
devnums = ifc.ifc_len / sizeof(struct ifreq);
// malloc ifc.ifc_buf and get IFCONF list
ifc.ifc_buf = malloc(ifc.ifc_len);
memset(ifc.ifc_buf,0x0,ifc.ifc_len);
if(ioctl(sfd,SIOCGIFCONF,&ifc) == -1)
{
perror("ioctl - SIOCGIFCONF : ");
return -1;
}
for(i = 0; i < devnums; i++,ifc.ifc_req++)
{
// idfy dev
if( strcmp(ifc.ifc_req->ifr_ifrn.ifrn_name,"lo") && ifc.ifc_req->ifr_ifrn.ifrn_name != 0)
{
ifr = ifc.ifc_req;
// IP address
struct sockaddr_in *a = (struct sockaddr_in *) &ifr->ifr_addr;
printf("%s",inet_ntoa(a->sin_addr));
printf("\n");
//get IFHWADDR
if(ioctl(sfd,SIOCGIFHWADDR,ifr) == -1)
{
perror("ioctl - SIOCGIFHWADDR : ");
return -1;
}
}
}
memcpy(macaddr,ifr->ifr_hwaddr.sa_data,sizeof(macaddr));
for(i = 0; i < ETHER_ADDR_LEN; i++)
{
printf("%02x ",macaddr[i]);
}
printf("\n");
close(sfd);
// free(ifc.ifc_buf); <- ?? error
return 0;
}
EDIT
I've replaced the following line:
printf("%02x ",macaddr[i]);
with
printf("%02x ", (macaddr[i] & 0xff));
Try this:
printf("%02x ", (unsigned char)macaddr[i] & 0xff);
We specify the minimum field width in the format string. So to make sure that the value will look exactly as a single byte, you can leave only the first 16 bits by applying a bit mask.

DBus : transmit a Data Array but crash

I would like to transmit a data array from one application to the other via DBus.
My code as below:
server.c:
/* server.c */
#include <dbus/dbus.h>
#include <stdbool.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
DBusHandlerResult filter_func(DBusConnection *connection,
DBusMessage *message, void *usr_data)
{
DBusMessage *reply;
dbus_bool_t handled = false;
char *pReadData;
unsigned char len;
unsigned char i;
DBusError dberr;
dbus_error_init(&dberr);
printf("pReadData = %x\n", (unsigned int)pReadData);
if(FALSE == dbus_message_get_args(message, &dberr, DBUS_TYPE_ARRAY,
DBUS_TYPE_BYTE, &pReadData, &len, DBUS_TYPE_INVALID) && 0 != len)
{
//printf("len = %d\n");
//printf("receiver data error\n");
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
if(0 == len)
return DBUS_HANDLER_RESULT_HANDLED;
printf("len = %d, ", len);
for( i = 0; i < len; i++)
printf("%#2x ", (unsigned char)pReadData[i]);
printf("\n");
handled = true;
printf("pReadData = %x\n", (unsigned int)pReadData);
/*if one free pReadData, it will crash!*/
//dbus_free_string_array((char**)&pReadData);
return (handled ? DBUS_HANDLER_RESULT_HANDLED :
DBUS_HANDLER_RESULT_NOT_YET_HANDLED);
}/*filter_func*/
int main(int argc, char *argv[])
{
DBusError dberr;
DBusConnection *dbconn;
dbus_error_init(&dberr);
dbconn = dbus_bus_get(DBUS_BUS_SESSION, &dberr);
if (!dbus_connection_add_filter(dbconn, filter_func, NULL, NULL)) {
return -1;
}
dbus_bus_add_match(dbconn, "type='signal',interface='gaiger.Drstein.Demonstration'", &dberr);
while(dbus_connection_read_write_dispatch(dbconn, -1)) {
/* loop */
}
return 0;
}/*main*/
And client.c
#include <dbus/dbus.h>
#include <stdbool.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int db_send(DBusConnection *dbconn)
{
DBusMessage *dbmsg;
char *pSendData;
unsigned char len;
unsigned char i;
pSendData = (char *)malloc(256);
dbmsg = dbus_message_new_signal("/client/signal/Object",
"gaiger.Drstein.Demonstration", "Test");
len = 6;
for(i = 0; i < len; i++)
pSendData[i] = (unsigned char)i;
if (!dbus_message_append_args(dbmsg, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE,
&pSendData, len, DBUS_TYPE_INVALID))
{
return -1;
}
if (!dbus_connection_send(dbconn, dbmsg, NULL)) {
return -1;
}
dbus_connection_flush(dbconn);
printf("send message : len = %d, ", len );
for( i = 0; i < len; i++)
printf("%#x ", (unsigned char)pSendData[i]);
printf("\n");
dbus_message_unref(dbmsg);
free(pSendData);
return 0;
}/**/
int main(int argc, char *argv[])
{
unsigned int i;
DBusError dberr;
DBusConnection *dbconn;
dbus_error_init(&dberr);
dbconn = dbus_bus_get(DBUS_BUS_SESSION, &dberr);
#if(1)
for(i = 0; i < 3; i++)
db_send(dbconn);
#else
while(dbus_connection_read_write_dispatch(dbconn, -1)) {
db_send(dbconn);
}
#endif
dbus_connection_unref(dbconn);
return 0;
}
The code works in Ubuntu 14.4, x86-64, but it crash in printing received data in Fedora 21, x86-32, virtual machine.
For the line :
if(FALSE == dbus_message_get_args(message, &dberr, DBUS_TYPE_ARRAY,
DBUS_TYPE_BYTE, &pReadData, &len, DBUS_TYPE_INVALID) && 0 != len)
I know the pointer pReadData would be allocated by dbus itself, the address value after this line is 0x90000 in Fedora 21, it is very odd number.
How should I do to avoid crash but print received data values in Fedora 21 x86 32bit?
Thank your help.
The documentation for dbus_message_get_args says to look at dbus_message_iter_get_fixed_array, and there we see that the len argument is a pointer to an integer (since in DBus "Arrays have a maximum length defined to be 2 to the 26th power or 67108864 (64 MiB).") but you are passing a pointer to an unsigned char. Use int len; on line 15 of the server.
Also you should not assume that an int and a pointer are the same size, and instead use a long to print the pointer.
printf("pReadData = %lx\n", (unsigned long)pReadData);

Low Level IO with Crypt

I am trying to compare a encrypted string that is taken from each line of a file to AAAA-ZZZZ until it finds its match of the password. I am guaranteed that the user password is of 4 characters. What I am trying to do is take in the file using LowLevel IO and output to a new file with the decrypted passwords of each line. I am not the best at C programming yet so please be gentle. I need direction on how to create an array or list going from AAAA all the way to ZZZZ and then comparing each to the decrypted version of the file line.
How to decrypt the file line by line and save it to a char []
How to compare each line to another char [] until password is found
For Example:
if the line is $1$6gMKIopE$I.zkP2EvrXHDmApzYoV.B. and the next line is $1$pkMKIcvE$WQfqzTNmcQr7fqsNq7K2p0. Assuming the resulting password after decryption is ABSZ and TAZE the new file will result it ABSZ on the first line and TAZE for the second line.
This is what I have so far:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void pdie(const char *);
void die(const char *);
#define BUFFER_SIZE 1024
int main(void)
{
char *pass;
int rfd;
int wfd;
char buffer[BUFFER_SIZE];
char *bp;
int bufferChars;
int writtenChars;
if ((rfd = open("pass.txt", O_RDONLY, 0)) < 0)
pdie("Open failed");
if ((wfd = open("passout.txt", O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0)
pdie("Open failed");
while (1)
{
if ((bufferChars = read(rfd, buffer, BUFFER_SIZE)) > 0)
{
printf("%s", buffer);
bp = buffer;
pass = crypt(getpass(all(4,4,'a','z')), *bp);
printf(pass);
while (bufferChars > 0)
{
if ((writtenChars = write(wfd, bp, bufferChars)) < 0)
pdie("Write failed");
bufferChars -= writtenChars;
bp += writtenChars;
}
}
else if (bufferChars == 0)
break;
else
pdie("Read failed");
}
close(rfd);
close(wfd);
return 0;
}
void pdie(const char *mesg) {
perror(mesg);
exit(1);
}
void die(const char *mesg) {
fputs(mesg, stderr);
fputc('\n', stderr);
exit(1);
}
int inc(char *c,char begin, char end){
if(c[0]==0) return 0;
if(c[0] == end){ // This make the algorithm to stop at char 'f'
c[0]=begin; // but you can put any other char
return inc(c+sizeof(char), begin, end);
}
c[0]++;
return 1;
}
int all(int a, int n,char begin, char end){
int i,j;
char *c = malloc((n+1)*sizeof(char));
for(i=a;i<=n;i++){
for(j=0;j<i;j++) c[j]=begin;
c[i]=0;
do {
printf("%s\n",c);
} while(inc(c,begin,end));
}
free(c);
}
here is the file:
$1$6gMKIopE$I.zkP2EvrXHDmApzYoV.B.
$1$pkMKIcvE$WQfqzTNmcQr7fqsNq7K2p0
$1$0lMKIuvE$7mOnlu6RZ/cUFRBidK7PK.

Convert Linux C Char Array to Int

need some advice on this one as im struggling abit and cannot figure it out.
i have a file that gets updated on a PC to indicate a system ran and what time it ran. i am writing a very simple linux console app (will eventually be a nagios plugin). that reads this file and responds depending on what it found within the file.
i am a total newbie to programming on Linux and using C so please be patient and if you would explain any answers it would really be appreciated.
basically i want to convert a char array containing 5 characters into an integer, however the 5th char in the array is always a letter. so technically all i want to-do is convert the first 4 chars in the array to a integer... how?? ive tried multiple ways with no success, my problem is that presently i do not have a good grasp of the language so have no real ideas on what it can and cannot do.
here is the source to my program.
basically the buf array will be holding a string taken from the file that will look something like this
3455Y (the number will be random but always 4 chars long).
Sorry for the poor formatting of the code, but i cannot get this stupid window for love nor money to format it correctly....
include <fcntl.h>
include <unistd.h>
include <stdio.h>
include <stdlib.h>
include <time.h>
include <string.h>
define COPYMODE 0644
int main(int argc, char *argv[])
{
int i, nRead, fd;
int source;
int STATE_OK = 0;
int STATE_WARNING = 1;
int STATE_CRITICAL = 2;
int STATE_UNKNOWN = 3;
int system_paused = 0;
char buf[5];
int testnumber;
if((fd = open(argv[1], O_RDONLY)) == -1)
{
printf("failed open : %s", argv[1]);
return STATE_UNKNOWN;
}
else
{
nRead = read(fd, buf, 5);
}
close(source);
if (buf[4] == 'P')
{
printf("Software Paused");
return STATE_WARNING;
}
else
{
return STATE_OK;
}
time_t ltime; /* calendar time */
struct tm *Tm;
ltime=time(NULL); /* get current cal time */
Tm=localtime(&ltime);
int test;
test = Tm->tm_hour + Tm->tm_min;
printf("%d", test);
printf("%d", strtoi(buf));
}
You can use sscanf to do the job:
int num = 0;
sscanf(buf, "%4d", &num);
Then num should hold the number from the line in the file.
You can use atoi
atoi requires one char * argument and returns an int.
If the string is empty, or first character isn't a number or a minus sign, then atoi returns 0.If atoi encounters a non-number character, it returns the number formed up until that point
int num = atoi(buf);
if you want to convert the first four characters of a string to an integer do this:
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdint.h>
uint8_t convertFirstFourChars(char * str, uint32_t *value){
char tmp[5] = {0};
strncpy((char *) tmp, str, 4);
*value = strtoul(tmp);
return errno;
}
then call / test this function like this
#include <stdint.h>
#include <stdio.h>
int main(int argc, char **argv){
char test1[5] = "1234A";
char test2[5] = "ABCDE";
uint32_t val = 0;
if(convertFirstFourChars((char *) test1, &val) == 0){
printf("conversion of %s succeeded, value = %ld\n", test1, val);
}
else{
printf("conversion of %s failed!\n", test1);
}
if(convertFirstFourChars((char *) test2, &val) == 0){
printf("conversion succeeded of %s, value = %ld\n", test2, val);
}
else{
printf("conversion of %s failed!\n", test2);
}
return 0;
}
FWIW, don't use atoi(...) because it converts any string to an integer regardless of its validity as a number. atoi("foo") === 0.
this is as much of your code as I was able to recover from the formatting:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <time.h>
#define COPYMODE 0644
int main(int argc, char *argv[])
{
int i, nRead, fd;
int source;
int STATE_OK = 0;
int STATE_WARNING = 1;
int STATE_CRITICAL = 2;
int STATE_UNKNOWN = 3;
int system_paused = 0;
char buf[5];
int testnumber;
if((fd = open(argv[1], O_RDONLY)) == -1)
{
printf("failed open : %s", argv[1]);
return STATE_UNKNOWN;
}
else
{
nRead = read(fd, buf, 5);
}
close(source);
if (buf[4] == 'P')
{
printf("Software Paused");
return STATE_WARNING;
} else {
return STATE_OK;
}
time_t ltime; /* calendar time /
struct tm Tm;
ltime=time(NULL); / get current cal time */
Tm=localtime(&ltime);
int test;
test = Tm->tm_hour + Tm->tm_min;
printf("%d", test);
printf("%d", strtoi(buf));
}
this is the version that does what you specified:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <time.h>
#define COPYMODE 0644
int main(int argc, char *argv[])
{
int i, nRead, fd;
int source;
int STATE_OK = 0;
int STATE_WARNING = 1;
int STATE_CRITICAL = 2;
int STATE_UNKNOWN = 3;
int system_paused = 0;
char buf[5];
int testnumber;
if((fd = open(argv[1], O_RDONLY)) == -1)
{
printf("failed open : %s", argv[1]);
return STATE_UNKNOWN;
}
else
{
nRead = read(fd, buf, 5);
}
close(source);
if (buf[4] == 'P')
{
printf("Software Paused");
return STATE_WARNING;
}/* else {
return STATE_OK;
buf[4] = 0;
} */
time_t ltime; /* calendar time */
struct tm *Tm;
ltime=time(NULL); /* get current cal time */
Tm=localtime(&ltime);
int test;
test = Tm->tm_hour + Tm->tm_min;
printf("%d\n", test);
printf("%d\n", atoi(buf));
}
The biggest problem with your code was the if statement with the returns in each branch, insuring that nothing after the if statement was ever executed.

Resources