How to trim a string in C

Trim a string

The problem of removing leading and trailing whitespace characters in strings occurs in programming quite often. Here is a solution.

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

void trim (char *dest, char *src); 

int main (int argc, char **argv)
    char inbuf [1024];
    char outbuf [1024];

    printf ("Type a string : ");
    while (fgets (inbuf, 1024, stdin) != NULL) {
        trim (outbuf, inbuf);      
        printf ("input string -%s-\n\n", inbuf);
        printf ("string -%s-\n\n", outbuf);
        printf ("Type a string : ");


// trim: leading and trailing whitespace of string
void trim (char *dest, char *src)
    if (!src || !dest)

    int len = strlen (src);

    if (!len) {
        *dest = '\0';
    char *ptr = src + len - 1;

    // remove trailing whitespace
    while (ptr > src) {
        if (!isspace (*ptr))


    char *q;
    // remove leading whitespace
    for (q = src; (q < ptr && isspace (*q)); q++)

    while (q < ptr)
        *dest++ = *q++;

    *dest = '\0';

We can compile and run the above program.… Read more

Network Socket Programming using TCP in C

1.0 Client-server model

Client - Server System

Client server model is a software architecture paradigm prevalent in distributed applications. A server has information resources and processes that provide answers to queries and other services to remote clients over the network. Some of the examples of these services are booking an airline ticket and/or a room in a hotel, sending a file to a client, sending a mail message to another person (client), etc.… Read more

Signals in Linux


1.0 Signals

Signals are software interrupts that are delivered to a process by the kernel. A signal indicates that an event has occurred and the process must take note of it. A signal is delivered asynchronously to a process. Whatever the process was doing is suspended and the processing of the signal takes place immediately.… Read more

POSIX Threads Synchronization in C

1.0 POSIX Threads Synchronization

POSIX Threads provide multiple flows of execution within a process. The threads have their own stacks but share the global data and heap. So the global variables are visible to multiple threads. Also, the threads need to synchronize their actions so that they jointly realize the overall objectives of the process they belong to.… Read more