Skip to main content

Posts

Showing posts with the label c program

C Traps & Pitfalls Book PDF Online by Andrew Koenig

C Traps & Pitfalls Book PDF Online by Andrew Koenig C Traps and Pitfalls is a slim computer programming book by former AT&T researcher and programmer Andrew Koenig, its first edition still in print in 2005, which outlines the many ways in which beginners and even sometimes quite experienced C programmers can write poor, malfunctioning and dangerous source code. It evolved from an earlier technical report published internally at Bell Labs, but is now available online in pdf form. <br> Happy coding.

UDP Traffic Generator Client Side C code

Learning Networking basics using C programs, to start with here is simple UDP client side code, Why to start with UDP because its simple, no need of connection handshake like TCP . This code sends continues UDP traffic over network, depending on the payload (ie send_buf) and delay between each transfer, rate at which data is pumped over network is calculated. Example: this client program is sending constant length 0f 1400 (in sendto function), so if you keep delay as 1s then data transfer rate will be 1400 per sec, decrease the delay to pump traffic at high rate. You need UDP server side code for running this client. udp client #include #include #include #include #include #include #include #include /* memset() */ #include /* select() */ #define REMOTE_SERVER_PORT 1500 #define MAX_MSG 1600 int main() { int sd, rc, i; struct sockaddr_in cliAddr, remoteServAddr; struct hostent *h; char *send_buf; unsigned int count=0; int reply; send_buf= (c...

UDP Traffic Generator Server Side C code

Learning Networking basics using C programs, to start with here is simple UDP server side code, Why to start with UDP because its simple, no need of connection handshake like TCP. udp server #include <sys/types.h>; #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <stdio.h> #include <unistd.h>/* close() */ #include <string.h> /* memset() */ #define LOCAL_SERVER_PORT 1500 #define MAX_MSG 1500 int main() { int sd, rc, n, cliLen; struct sockaddr_in cliAddr, servAddr; char msg[MAX_MSG]; int count; int prev_count=0; /* socket creation */ sd=socket(AF_INET, SOCK_DGRAM, 0); //create unix socket if(sd printf("cannot open socket \n"); exit(-1); } /* bind local server port */ servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = inet_addr("1.168.3.100"); //using fixed IP for simplicity servAddr.sin_...

Loop Unrolling or Loop unwinding in C

What is Loop Unrolling or Loop unwinding in C? Loop unwinding, also known as loop unrolling , is a loop transformation technique that attempts optimize a program's execution speed at the expense of its size. The goal of loop unwinding is to increase the program's speed by reducing (or eliminating) the "end of loop" test on each iteration. Loops can be re-written as a sequence of independent statements which eliminates the loop controller overhead. The major side effects of loop unrolling is The increased register usage in a single iteration to store temporary variables (though much will depend on possible optimizations), which may hurt performance. The code size expansion after the unrolling, which is undesirable for embedded applications and for purposes of code readability. Large code can also cause an increase in instruction cache misses, which may adversely affect performance. A simple example A procedure in a computer program is to delete 100 items from a collec...

Data Structures Linked List Reverse

simple linked list Data Structures -- Linked List -- Reverse /* * Simple operations on linked list. If any problem */ #include /* * Data structure used, its simple :) */ Typedef struct linked_list_s { int value; struct linked_list_s *next; }linked_list_t; /* * Add a node at the end of the list. */ Linked_list_t* add_node(linked_list_t *head, int value) { linked_list_t *newNode = NULL; linked_list_t *node = head; linked_list_t *prev = head; newNode = (linked_list_t *)calloc(1, sizeof(linked_list_t)); newNode->value = value; while(node) { prev = node; node = node->next; } if(prev == node) return newNode; prev->next = newNode; return head; } /* * delete a specified node from the list. */ Linked_list_t* delete_node(linked_list_t *head, int value) { linked_list_t *node = NULL; linked_list_t *prev = NULL; for(node = head; node != NULL; prev = node, node = node->next) { if(node->value == value) { //Check for head node modification if(prev =...

ntfsprogs and Fuse Compilation errors and Solution here

Got some luck to compile ntfsprogs. Ntfsprogs are a collection of utilities for doing stuff with NTFS volumes. Steps to compile ntfsprogs . 1. get the FUSE and compile it. $ tar xvzf fuse-2.7.4.tar.gz $ ./configure --disable-kernel-module $ make getting error while compiling examples dir. libtool: link: gcc -Wall -W -Wno-sign-compare -Wstrict-prototypes -Wmissing-declarations -Wwrite-strings -g -O2 -fno-strict-aliasing -o .libs/fusexmp fusexmp.o -pthread -pthread ../lib/.libs/libfuse.so -ldl ../lib/.libs/libfuse.so: undefined reference to `clock_gettime' make[1]: Leaving directory `/home/bhagwat/fuse-2.7.4/example' Solution is $ cd examples open Makefile go to line no 205 change the option from -ldl to -lrt $ cd ../make $ make install FUSE will be installed in default dir ie /usr/local/lib Get the ntfsprogs from linux-ntfs. untar ntfsprograms $ tar xvzf ntfsprogs-2.0.0.tar.gz $ ./configure --enable-ntfsmount still getting same error smount ntfsmount-ntfsmount.o ntfsmount-ut...

Calling User Space Program From Kernel Space

Invoking user mode application from kernel modules, yes its possible with help of CALL_USERMODEHELPER . With the following kernel API, we can invoke user mode application from Kernel modules/threads. int call_usermodehelper (char * path, char ** argv, char ** envp, int wait); path: pathname for the application. argv: null-terminated argument list. envp: null-terminated environment list. wait: wait for application to finish and return status. Example: Kernel Module: #include #include char name[]="user_program"; static int init_function(void) { int ret; char *argv[] = {name, "hello", "world", NULL }; static char *envp[] = { "HOME=/", "TERM=linux", "PATH=/sbin:/usr/sbin:/bin:/usr/bin", NULL }; printk("We r in init_function\n"); ret= call_usermodehelper(name, argv, envp, 1); if ( ret #include int...

It's a Bigger World than Java and C++

We hear a lot about Java and C++, but that doesn't mean they're the only languages developers are using. Tokeneer was developed for the U.S. National Security Agency (NSA), an outfit known for keeping things secret. Which makes it even more surprising that not only did the NSA acknowledge Tokeneer's existence, but they released it as open source software. In a nutshell, Tokeneer is a proof-of-concept of what's called "high-assurance software engineering." Secure software, in other words. Software you can trust. Software that must work correctly or else the consequences could be calamitous. And software that's written in Ada—yes, Ada—and developed using Praxis High Integrity Systems ( www.praxis-his.com ) Correctness-by-Construction (CbyC) methodology, the SPARK Ada language ( www.sparkada.com ), and AdaCore's GNAT Pro environment ( www.adacore.com ). The project demonstrates how to meet or exceed all those things that are necessary to achieve hig...

C Programming Caution while using execlp function

What is C Programming Caution while using execlp function? programming caution while using execl function series. execlp function series most of the time are used with fork() system call; If the requirement is there to kill the process started by execl function, then one caution need to take care, as execl functions will replace complete child process image with the new process image, This means new process started is having new pid and not as same as child pid. In order to kill the process we need to call getpid function in calling function and store this pid in temp file and while killing this new process use kill(pid) system call. Example usage assuming in pid is stored in /var/childpid. fptr = fopen("/var/childpid","r"); if(fptr != NULL) fgets(child_pid,10,fptr); else printf("Can't open childpid file"); close(fptr); child_pid[strlen(child_pid)-1] = '\0'; sprintf(cmd,"...

Use of Execlp Functions C program Explained

Below code listing illustrates usage of execl function series, and talks about how to redirect the output from these functions. Here is trick to redirect the output from execlp command series In other words implematiation of "ls -l >/var/test.log" first open file using "open" system call #include #include #include int open(const char *pathname, int flags); then duplicate this file pointer with stdio file pointers stdio file pointer are 0 for stdin 1 for stdout and 2 for stderr use of dup2 dup and dup2 create a copy of the file descriptor oldfd. int dup2(int oldfd, int newfd); here is c example implementation in function; int spawn(char* cmd) { pid_t child_pid; int fptr,fptr2; char tmp_devfs[20]; int child_status=-1,ret=-1; // printf("executing cmd=%s\n",cmd); fptr=open("/var/test.log",O_RDWR); /*create new process */ child_pid = fork(); if (child_pid != 0){ /* This is the parent process. */ ret = c...

Get Mounted File System Type C function

How to get Mounted file system type using C program? Here is trick to get mounted file system type or say this trick can be applied to get variable from linux; This is simple combination of "grep" and "awk" commands. check out below; this function takes mounted point name like where you have mounted the disk example /dev/sda1 is being mounted at /mnt/test so the input argument to this function is test and the output should get is /dev/sda1 filesytem type. If you type mount command you will get the file type on my system with one pen drive; it shows dev/sda1 on /mnt/JetFlash type ext3 (rw) input to this function is JetFlash and I will get return as ext3 which is file system type. Description : returns mounted FS type char *get_fs_type(char *mount_point_name) { char temp[20]; char cmd[100],*ret_p; FILE *fptr; sprintf(cmd,"/sbin/fdisk -l | grep %s | awk '{print $6,$7}' > /var/mpt",mount_point_name); system(cmd); fptr = fopen(...

Palindrome Number Checking for Int C program Functions

Write a c program to know if given number is palindrome or not? Well first try to digg out what is palindrome? A palindrome is a word, phrase, number or other sequence of units that can be read the same way in either direction. Palindrome example is TENT on either direction characters are same. The most familiar palindromes, in English at least, are character-by-character: the written characters read the same backwards as forwards. Palindromes may consist of a single word ( civic , level , racecar , rotator , Malayalam ), or a phrase or sentence ("Was it a rat I saw?", "Wasilla: All I saw", "Mr. Owl ate my metal worm", "Sit on a potato pan, Otis", "Neil, a trap! Sid is part alien!", "Go hang a salami I'm a lasagna hog.", "Satan, oscillate my metallic sonatas", "I roamed under it as a tired nude Maori"). Punctuation, case and spacing are usually ignored, although some (such as "Rats live on no evil...

strtok Simple Usage Example string words seperate

How to get string words separate? Separate each word from string of /share/test/ Here is simple code snippet which also demonstrate use of string token ( strtok() function) ; Below is simple C code; #include #include int main() { char df_buf[120]; char *name1,*result; int i; char *tmp; char str_array[7][50]; strcpy(df_buf,"/share/test/path/"); result=strtok(df_buf,"/"); //printf("%s\n",result); while(result!=NULL) { tmp=strdup(result); strcpy(str_array[i],tmp); result=strtok(NULL,"/"); printf("%s and %s\n",result,tmp); i++; } printf("i=%d\n",i); printf("%s\n",str_array[0]); printf("%s\n",str_array[1]); printf("%s\n",str_array[2]); return 0; } The output will be share test path ie /share/test/path string is separated into words;

Delete Last Char in String C program Simple Way

How to delete the last character in a string? Lets say I have a string "/data/share/" I want to delete the last character from the string ie "/" so that output will be "/data/share"; Here are some methods to do this in C language. one way could be use of strncat() function; char * strncat ( char *restrict s1 , const char *restrict s2 , size _ t n ); The strncat() function appends not more than n characters from s2, and then adds a terminating `\0'. #include Another simple way is, say the string variable is str_p Then simply put str_p[(strlen(str_p)-1)] = '\0'; And you are done;

Display Date Time C-Function use-strftime()-function

I was looking for a c function which prints date in format Equivalent to %Y-%m-%d (the ISO 8601 date format). And also want to display The time in a.m. or p.m. notation. As In the POSIX locale this is equivalent to HH:MM:SS pm or am. I got some C code like curr_time = time( NULL ); strncpy( time_string, ( ctime( &curr_time ) ), MAX_TIME_LENGTH ); time_string[ strlen( time_string ) - 1 ] = 0; printf("%s:-> ", time_string ); which uses time function and gives time output; put this output in some temp file then read it as desired. Looks complex, need simple solution ahaa.. I discovered strftime() function , which made my time display life easier, rather than previous complex approach. And believe me its just four lines of C code. declare variables: struct tm *ptr; time_t ltime; char *year,*local_time; Initialize pointers year=(char*)(malloc(sizeof(char))); local_time=(char*)malloc(sizeof(char)); Here we go ltime = time(NULL); /* get...

Get Disk Details Values in C function Nice one

I want to get the disk details in the format like type, size, used and available space; The output should be * disk_details[0] contains mounted FS type * disk_details[1] contains mounted FS size * disk_details[2] contains mounted FS used space * disk_details[3] contains mounted FS Available space * disk_details[4] contains mounted FS % used space where FS is file system Basically i want the output of $df -h | grep /mnt in a c function, here is the c function which takes double dimension array as in input; updates it with disk details. int get_disk_details(char disk_details[][50]) { FILE *fp; char df_buf[90]; char *name1,*result; int i; char *tmp; system("df -h | grep /mnt | awk '{print $6,$2,$3,$4,$5}' > /var/temp2.txt"); fp= fopen("/var/temp2.txt","r"); i=0; while(fgets(df_buf,80,fp)) { ...

Delete a line in a file C Programming Example

Why this program? This simple c example is answer to below questions. How can i delete some specific line from .txt file? Is there a way of deleting the whole line using c program? How to delete a line in a file C Program ming? Here are simple steps to do; 1) Open a temp file for writing. 2) Open the xyz.txt file for reading. ie source file. 3) copy from source file to temp file using gets (). 4) compare the char or string to be deleted is there from gets, if it is there dont copy that line to temp file, else copy. 5) Close both files 6) Delete the xyz.txt file 7) Rename the temp file, to xyz.txt. And here is C program that would delete the first or last line from a file. #include #define CORN_CONF_FILE "/var/spool/cron/crontabs/root" #define CORN_CONF_TMP_FILE "/var/spool/cron/crontabs/tmp" int del_cron_conf_line(); int main() { int ret; ret = del_cron_conf_line(); printf("ret=%d",ret); return 0; } int del_cron_conf_line() { int ret=...

C Program Usage fseek fopen ftell and fprintf

I need a c program to write update values in a file. Here is simple logic for it. steps. open file. set the file pointer using fseek. (same as lseek) write the value. close the file. int fseek(FILE *stream, long offset, int whence); off_t lseek(int fildes, off_t offset, int whence); The lseek function repositions the offset of the file descriptor fildes to the argument offset according to the directive whence as follows: SEEK_SET The offset is set to offset bytes. SEEK_CUR The offset is set to its current location plus offset bytes. SEEK_END The offset is set to the size of the file plus offset bytes. Some more notes on this; From step one one can open file in read mode or r+ mode; then in second step set the file pointer to the end of file using fseek, with SEEK_END. using fprintf update the values in file. The other way to do this is open file in append mode, then no need to setting file pointer, as if file...

C Program for Counting Number of lines from File

C program for counting number of lines from a file. I was in need to count no of lines from a file, written simple program to do that. int no_of_lines() { int i=0,j=0; /* declare a char array */ FILE *file; /* declare a FILE pointer */ char *line; char *temp=NULL; file = fopen("/rdisk0/var/log/nas2msg", "r"); /* open a text file for reading */ if(file==NULL) { return 9; } else { while( (i=getc(file)) !=EOF) { /* print the file one line at a time */ //i=getc(file); if(i == '\n') printf("line %d",j++); } fclose(file); return j; } }