Implementing Template-Based Text Generation in C

Problem Overview

Consider a scenario where you need to generate personalized content for users. When a customer logs into an e-commerce site, they might see a welcome message containing their specific information. This requires combining a predefined text template with user data from a database.

The challenge is to create a system that can:

  1. Read a template file containing placeholders
  2. Retrieve user data from a data source
  3. Replace placeholders with actual data
  4. Generate the final customized text

Template Processing Approach

A naive approach would involve hardcoding the output format and manually inserting data values. However, a more elegant solution is to create a template processor that can interpret special markers in the template and replace them with corresponding data.

In our implementation, we'll use dollar signs followed by numbers as placeholders (e.g., $0, $1, $2). These markers will represent positions in our data array where the actual values are stored.

Implementation

Template File

// greeting.txt
Dear $0,

Welcome back to our platform! We're excited to see you again.

Your profile information:
Name: $1 $2. $0
Address: $3 $4
City: $5, State: $6 $7

We hope you enjoy our services!

Best regards,
The Team

C Code Implementation

#include 
#include 
#include 

#define MAX_BUFFER_SIZE 256
#define MAX_LINE_LENGTH 1024

int main() {
    // Simulated user data retrieved from database
    char* userData[] = {"Smith", "John", "D.", "123", "Main St", "Springfield", "IL", "62701"};
    const int dataCount = sizeof(userData) / sizeof(userData[0]);
    
    // Open template file
    FILE *templateFile = fopen("greeting.txt", "r");
    if (!templateFile) {
        fprintf(stderr, "Error: Unable to open template file\n");
        return EXIT_FAILURE;
    }
    
    char currentLine[MAX_LINE_LENGTH];
    
    // Process each line of the template
    while (fgets(currentLine, sizeof(currentLine), templateFile)) {
        size_t lineLength = strlen(currentLine);
        
        // Remove newline character if present
        if (lineLength > 0 && currentLine[lineLength - 1] == '\n') {
            currentLine[lineLength - 1] = '\0';
        }
        
        // Process each character in the line
        for (int i = 0; currentLine[i] != '\0'; i++) {
            if (currentLine[i] == '$') {
                // Found a placeholder marker
                i++;
                if (currentLine[i] == '$') {
                    // Escaped dollar sign
                    printf("$");
                } else if (currentLine[i] >= '0' && currentLine[i] <= '9') {
                    // Numeric placeholder
                    int placeholderIndex = currentLine[i] - '0';
                    
                    if (placeholderIndex >= 0 && placeholderIndex < dataCount) {
                        printf("%s", userData[placeholderIndex]);
                    } else {
                        fprintf(stderr, "Error: Placeholder index out of range\n");
                        fclose(templateFile);
                        return EXIT_FAILURE;
                    }
                } else {
                    fprintf(stderr, "Error: Invalid placeholder format\n");
                    fclose(templateFile);
                    return EXIT_FAILURE;
                }
            } else {
                // Regular character
                putchar(currentLine[i]);
            }
        }
        
        // Add newline after processing each line
        putchar('\n');
    }
    
    // Close file and exit successfully
    fclose(templateFile);
    return EXIT_SUCCESS;
}

Code Explanation

The implementation follows these key steps:

  1. Define an array containing the user data that will replace placeholders
  2. Open and read the template file line by line
  3. For each character in the line:
    • If it's a regular character, output it directly
    • If it's a dollar sign, check the next character
      • If another dollar sign, output a single dollar sign
      • If a digit, replace with corresponding data from the array
      • Otherwise, report an error
  4. Continue until all lines are processed

Key Features

  • Template-based approach allows for flexible content formatting
  • Separation of content structure and data
  • Error handling for invalid placeholders
  • Efficient processing of large templates
  • Support for escaped dollar signs ($$)

Practical Applications

This technique can be used in various scenarios:

    >Email generation systems
    >Report generation with variable data
    >Invoice creation
    >Certificate printing
    >Personalized user notifications

Tags: c programming template processing text generation file processing

Posted on Thu, 07 May 2026 19:44:26 +0000 by adeenutza