c program to parsing a string with delimiter in-between [using strtok]

C program to parsing a string with delimiter in-between [using strtok]


#include <stdio.h>

#include <string.h>

int main (void)
{
  char str[] = "neelkanth<delimiter>google<delimiter>stallone";
  char *temp = str;
  char *delim = "<delimiter>";
  char *token;

  do {
    printf("Before Tokenizing : %s\n", temp);
    token = strstr(temp , delim);

    if (token)
      *token = '\0';

    printf("After Tokenizing :%s\n", temp);
    temp = token+strlen(delim);


  }while(token!=NULL);


  return 0;
}


Neelkanth_98$ ./a.out
Before Tokenizing : neelkanth<delimiter>google<delimiter>stallone
After Tokenizing :neelkanth
Before Tokenizing : google<delimiter>stallone
After Tokenizing :google
Before Tokenizing : stallone
After Tokenizing :stallone


C program to write environment variables and their values into file and read the variables and their values from the file (using strtok)

C program to write environment variables and their values into file and read the variables and their values from the file (using strtok)


Neelkanth_39$ cat neel.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

void func_read();
void func_write(char **envp);

void func_write(char **envp)
{

    FILE *fp = NULL;
    char a[1000];
    int i = 0;
    int len = 0;

    printf("\n WRITING ENVIRONMENT VARIABLES INTO FILE \n");
    fp = fopen ("file.txt", "w");
    if (fp == NULL){
        printf("failed to open %s", "file.txt");
        return ;
    }


    while(envp[i] != NULL) {
          strcat(a , envp[i]);
          strcat(a , "@");
          i++;
    }
    printf("%s\n",a);
    len = strlen(a);

    a[len+1] = '\0';

    fwrite( a, strlen(a), 1, fp);
    fclose(fp);

    func_read();

}

void func_read()
{
    char **envp;
    char a[1000];
    FILE *fp;
    char *pt;
    char temp[10][100];
    int i = 0;

    printf("\n READING ENVIRONMENT VARIABLES AND THEIR VALUES FROM FILE \n");
    fp = fopen ("file.txt", "r");
    if (fp == NULL) {
        printf("failed to open %s", "file.txt");
        return ;
    }

    fscanf(fp, "%s", a);

    pt = strtok (a,"@");
    while (pt != NULL) {
        printf("%s\n", pt);
        strcpy(temp[i], pt);
        pt = strtok (NULL, "@");
        i++;
    }
    printf("temp[0]: %s\n", temp[0]);
    printf("temp[1]: %s\n", temp[1]);
    printf("temp[2]: %s\n", temp[2]);

    char *name, *value;

    name = strtok(temp[0], "=");
    printf("name: %s\n", name);
    value = strtok(NULL, "=");
    printf("value: %s\n", value);

    return;

}

int main()
{

    char *envp[] = {"stallone=rambo" ,"google=god", "hrithik=me", NULL };

    printf("\n PASS ENVIRONMENT VARIABLES TO WRITE TO FILE FUNCTION \n");
    func_write(&envp[0]);

    return 0;
}




Output:


Neelkanth_39$ gcc neel.c
Neelkanth_39$ ./a.out

 PASS ENVIRONMENT VARIABLES TO WRITE TO FILE FUNCTION

 WRITING ENVIRONMENT VARIABLES INTO FILE
stallone=rambo@google=god@hrithik=me@

 READING ENVIRONMENT VARIABLES AND THEIR VALUES FROM FILE
stallone=rambo
google=god
hrithik=me
temp[0]: stallone=rambo
temp[1]: google=god
temp[2]: hrithik=me
name: stallone


c program to copy values from double pointer array into file

C program to copy values from double pointer array into file


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>


void func(char **envp)
{
    FILE *fp = NULL;
    fp = fopen ("dhcp", "w");
    if (fp == NULL){
        printf("failed to open %s", "dhcp");
        return ;
    }

    int i = 0;
    while(envp[i] != NULL) {
        fwrite( envp[i], strlen(envp[i])+1, 1, fp);

        i++;
    }
    fclose(fp);
}


int main()
{

    char *envp[] = {"stallone\0" ,"google\0", NULL };

    func(&envp[0]);

    return 0;
}


c program to write into file from array and read from the same file back into the array

C program to write into file from array and read from the same file back into the array 


#include <stdio.h>
#include <string.h>

int main()
{
    FILE *fp;
    char c[] = "this is tutorialspoint";
    char buffer[100];
    int read_buf = 0;

    /* Open file for both reading and writing */
    fp = fopen("file.txt", "w+");

    /* Write data to the file */
    fwrite(c, strlen(c) + 1, 1, fp);

/* Seek to the beginning of the file */ /* if this is not done then read would fail. always do SEEK_SET after fwrite and before performing fread*/

    fseek(fp, 0, SEEK_SET);


    read_buf = fread(buffer, strlen(c)+1, 1, fp);
    if (read_buf <= 0) {
        printf("read failed");
        return 0;
    }

    printf("%s\n", buffer);
    fclose(fp);

    return(0);
}


c program to implement file locking in a process

C program to implement file locking in a process


####################################################################
                                           PROGRAM 1
####################################################################
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
                    /* l_type   l_whence  l_start  l_len  l_pid   */
    struct flock fl = {F_WRLCK, SEEK_SET,   0,      0,     0 };
    int fd;

    fl.l_pid = getpid();

    if (argc > 1) 
        fl.l_type = F_RDLCK;

    if ((fd = open("lockdemo.c", O_RDWR)) == -1) {
        perror("open");
        exit(1);
    }

    printf("Press <RETURN> to try to get lock: ");
    getchar();
    printf("Trying to get lock...");

    if (fcntl(fd, F_SETLKW, &fl) == -1) {
        perror("fcntl");
        exit(1);
    }

    printf("got lock\n");
    printf("Press <RETURN> to release lock: ");
    getchar();

    fl.l_type = F_UNLCK;  /* set to unlock same region */

    if (fcntl(fd, F_SETLK, &fl) == -1) {
        perror("fcntl");
        exit(1);
    }

    printf("Unlocked.\n");

    close(fd);

    return 0;
}


####################################################################
                                           PROGRAM 2
####################################################################
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int lock_file(char *fname)
{
struct flock f;
int fd;
fd = open( fname, O_RDWR );
if( fd == -1 ) {
        //printf("Failed to open %s",fname);  /* error handling */
return fd;
}
f.l_type = F_WRLCK;
f.l_start = 0;
f.l_whence = SEEK_SET;
f.l_len = 0;
return fcntl( fd, F_SETLK, &f );
}
int unlock_file(char *fname)
{
struct flock f;
int fd;
fd = open( fname, O_RDWR );
if( fd == -1 ) {
        //printf("Failed to open %s",fname);  /* error handling */
return fd;
}
f.l_type = F_UNLCK;
f.l_start = 0;
f.l_whence = SEEK_SET;
f.l_len = 0;
return fcntl( fd, F_SETLK, &f );
}
int add_record( )
{
getchar();
}
int main()
{
int          state = 1;
char       filename[]="test.lock";
while(state != 0)
state = lock_file(filename);
add_record();
unlock_file(filename);
return 0;
}


C program to implement message queue in linux

C program to implement message queue in linux


Neelkanth_221$ cat mq_server.c

/*
 * server.c: Server program
 *           to demonstrate interprocess commnuication
 *           with System V message queues
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#include <sys/time.h>
#include <time.h>
#include <math.h>


#define SERVER_KEY_PATHNAME "mqueue_server_key"
#define PROJECT_ID 'M'
#define QUEUE_PERMISSIONS 0660

struct message_text {
    int qid;
    char buf [8100];
};

struct message {
    long message_type;
    struct message_text message_text;
};

void get_current_time(void)
{
    /* get current system time*/
    char buffer[26];
    struct tm* tm_info;
    struct timeval tv;

    gettimeofday(&tv, NULL);
    tm_info = localtime(&tv.tv_sec);

    strftime(buffer, 26, "%Y:%m:%d %H:%M:%S", tm_info);
    printf("server: current Time: %s.%ld\n", buffer, tv.tv_usec);

    return;
}


int main (int argc, char **argv)
{
    key_t msg_queue_key;
    int qid;
    struct message message;


    if ((msg_queue_key = ftok (SERVER_KEY_PATHNAME, PROJECT_ID)) == -1) {
        perror ("ftok");
        exit (1);
    }

    if ((qid = msgget (msg_queue_key, IPC_CREAT | QUEUE_PERMISSIONS)) == -1) {
        perror ("msgget");
        exit (1);
    }

    printf ("Server: Hello, World!\n");

    int count = 0;
    while (1) {
        // read an incoming message
        if (msgrcv (qid, &message, sizeof (struct message_text), 0, 0) == -1) {
            perror ("msgrcv");
            exit (1);
        }
        count ++;

        if(count == 1 || count == 50000)
        {
            printf("#####################################################################\n");
            printf("packet count  : %d\n", count);
            printf ("Server: message received from client:\n [%s]  message length: %ld\n",
                    message.message_text.buf, strlen(message.message_text.buf));
            get_current_time();
            printf("#####################################################################\n");
            if (count == 50000) {
                count = 0;
            }

            printf("\n\n\n");
        }


    }
}

Neelkanth_221$ cat mq_client.c

/*
 * client.c: Client program
 *           to demonstrate interprocess commnuication
 *           with System V message queues
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define SERVER_KEY_PATHNAME "mqueue_server_key"
#define PROJECT_ID 'M'

#include <sys/time.h>
#include <time.h>
#include <math.h>


char client_text[8192] = {'\0'};


struct message_text {
    int qid;
    char buf [8100];
};

struct message {
    long message_type;
    struct message_text message_text;
};


void get_current_time(void)
{
    /* get current system time*/
    char buffer[26];
    struct tm* tm_info;
    struct timeval tv;

    gettimeofday(&tv, NULL);
    tm_info = localtime(&tv.tv_sec);

    strftime(buffer, 26, "%Y:%m:%d %H:%M:%S", tm_info);
    printf("client: current Time: %s.%ld\n", buffer, tv.tv_usec);

    return;
}

int main (int argc, char **argv)
{
    key_t server_queue_key;
    int server_qid, myqid;
    struct message my_message, return_message;

    if (argc != 2)
    {
        printf("\n Enter a string \n");
        return 0;
    }

    strncpy(client_text, argv[1], sizeof(client_text));

    // create my client queue for receiving messages from server
    if ((myqid = msgget (IPC_PRIVATE, 0660)) == -1) {
        perror ("msgget: myqid");
        exit (1);
    }

    if ((server_queue_key = ftok (SERVER_KEY_PATHNAME, PROJECT_ID)) == -1) {
        perror ("ftok");
        exit (1);
    }

    if ((server_qid = msgget (server_queue_key, 0)) == -1) {
        perror ("msgget: server_qid");
        exit (1);
    }

    my_message.message_type = 1;
    my_message.message_text.qid = myqid;

    printf("########################################################################\n");
    printf("client: send  message to server : [%s] message length: [%ld] \n",client_text,
                              strlen(client_text));
    printf("########################################################################\n");


    strcpy(my_message.message_text.buf, client_text);

    // remove newline from string
    int length = strlen (my_message.message_text.buf);
    if (my_message.message_text.buf [length - 1] == '\n')
        my_message.message_text.buf [length - 1] = '\0';

    printf("########################################################################\n");
    printf("client: time stamp just 'Before' sending the message to server \n");
    get_current_time();
    printf("########################################################################\n");

    int i;
    for (i = 0; i < 50000; i++)
    {
        // send message to server
        if (msgsnd (server_qid, &my_message, sizeof (struct message_text), 0) == -1) {
            perror ("client: msgsnd");
            exit (1);
        }
        if ((i == 0) || (i == 49999))
        {
            printf("########################################################################\n");
            printf("client: time stamp just 'after' sending the message to server \n");
            printf("packet count : %d\n", i+1);
            get_current_time();
            printf("########################################################################\n");
        }
    }

    // remove message queue
    if (msgctl (myqid, IPC_RMID, NULL) == -1) {
        perror ("client: msgctl");
        exit (1);
    }
    printf ("Client: bye\n");
    printf ("\n\n\n");

    exit (0);
}

Output:
Neelkanth_221$ gcc -o server mq_server.c -lm
Neelkanth_221$ gcc -o client mq_client.c -lm

Neelkanth_221$ ./server &
[1] 32263
Neelkanth_221$ Server: Hello, World!

Neelkanth_221$ ./client asldfhalsdjkfhaslfhasldfhl
########################################################################
client: send  message to server : [asldfhalsdjkfhaslfhasldfhl] message length: [26]
########################################################################
########################################################################
client: time stamp just 'Before' sending the message to server
client: current Time: 2018:02:26 19:43:27.596650
########################################################################
#####################################################################
packet count  : 1
Server: message received from client:
 [asldfhalsdjkfhaslfhasldfhl]  message length: 26
server: current Time: 2018:02:26 19:43:27.596763
#####################################################################

########################################################################
client: time stamp just 'after' sending the message to server
packet count : 1
client: current Time: 2018:02:26 19:43:27.597185
########################################################################
########################################################################
client: time stamp just 'after' sending the message to server
packet count : 50000
client: current Time: 2018:02:26 19:43:27.817492
########################################################################
Client: bye

#####################################################################
packet count  : 50000
Server: message received from client:
 [asldfhalsdjkfhaslfhasldfhl]  message length: 26
server: current Time: 2018:02:26 19:43:27.818828
#####################################################################