Simple URL Shortener in C

 

 

Introduction

A URL shortener is a tool that converts long URLs into shorter, more manageable links that are easy to share and remember.
In this tutorial, we will create a basic URL shortener using the C programming language. The program will take a long URL as input
and generate a shortened version. This is a great way to learn about string manipulation and file handling in C.

Objective

The objective of this program is to implement a simple URL shortener that maps long URLs to short, custom identifiers.
We’ll be storing the long URL and its corresponding short URL in a file for future reference.

Code


#include 
#include 
#include 

#define MAX_URL_LENGTH 2048
#define SHORT_URL_LENGTH 6

// Function to generate a short URL (simple hash)
void generateShortURL(char *longURL, char *shortURL) {
    unsigned long hash = 5381;
    int c;
    
    // Generate a simple hash from the long URL
    while ((c = *longURL++)) {
        hash = ((hash << 5) + hash) + c;
    }
    
    // Convert hash to a string of characters
    snprintf(shortURL, SHORT_URL_LENGTH, "%lx", hash % 1000000); // Limit the length
}

// Function to store the long and short URL pair
void storeURL(char *longURL, char *shortURL) {
    FILE *file = fopen("urls.txt", "a");
    if (file == NULL) {
        printf("Could not open file for saving URL.\n");
        return;
    }
    
    fprintf(file, "Long URL: %s\nShort URL: %s\n\n", longURL, shortURL);
    fclose(file);
}

int main() {
    char longURL[MAX_URL_LENGTH], shortURL[SHORT_URL_LENGTH];
    
    // Input the long URL
    printf("Enter the long URL: ");
    fgets(longURL, MAX_URL_LENGTH, stdin);
    
    // Remove the newline character
    longURL[strcspn(longURL, "\n")] = 0;
    
    // Generate short URL
    generateShortURL(longURL, shortURL);
    
    // Display the short URL
    printf("Short URL: http://short.ly/%s\n", shortURL);
    
    // Store the URL pair in a file
    storeURL(longURL, shortURL);
    
    return 0;
}
    

Explanation of the Program

This program consists of a few important parts:

  • generateShortURL function: This function takes a long URL as input and generates a hash-based short URL. It simply creates a hash from the URL and then converts it into a string of numbers to create a unique short URL.
  • storeURL function: This function stores the long URL and its corresponding short URL in a text file named urls.txt. This allows us to persist the mapping between long and short URLs.
  • main function: The main function drives the program. It prompts the user to enter a long URL, generates a short URL using the generateShortURL function, displays it to the user, and then stores the mapping in a file using the storeURL function.

How to Run the Program

To run this program, follow these steps:

    1. Copy the code into a C file, for example, url_shortener.c.
    2. Open a terminal and navigate to the directory where the file is saved.
    3. Compile the program using a C compiler (e.g., GCC):
gcc url_shortener.c -o url_shortener
    1. Run the compiled program:
./url_shortener
  1. Enter the long URL when prompted, and the program will generate and display a short URL. It will also store the mapping in the urls.txt file.
© 2025 Learn Programming

 

5 Replies to “Simple URL Shortener in C”

  1. I simply couldn’t leave your website before suggesting that I really
    enjoyed the usual information an individual provide for your visitors?
    Is gonna be again often in order to check up on new posts

  2. Доброго!
    Долго не спал и думал как поднять сайт и свои проекты и нарастить DR и узнал от крутых seo,
    отличных ребят, именно они разработали недорогой и главное top прогон Xrumer – https://www.bing.com/search?q=bullet+%D0%BF%D1%80%D0%BE%D0%B3%D0%BE%D0%BD
    Линкбилдинг что работа требует внимательного подхода. Линкбилдинг быстрый позволяет ускорить продвижение. Линкбилдинг линкбилдинг стратегии помогают системно создавать ссылки. Секреты работы с Xrumer открывают новые возможности. Как увеличить DR сайта Ахрефс зависит от качества ссылок.
    seo вебкам, как в сео продвинуть сайт, Xrumer 2025: советы по настройке
    Прогон по базам форумов, продвижение тверских сайтов, аренда сайта с продвижением в
    !!Удачи и роста в топах!!

  3. I am really impressed with your writing skills as well as with
    the layout on your weblog. Is ths a paid theme or did you modify it yourself?
    Anyway keep up the excellent quality writing, it is rare to see a nice blog like
    this one today.

Leave a Reply to SeoNus Cancel reply

Your email address will not be published. Required fields are marked *