Parse Apache Config for DocumentRoot in C

Posted by Tully on Tue 22 December 2009

So I am now on my second week of learning the C programming language. I have been writing a lot of small programs just to get the hang of the code. I have written simple calculators, guess my number games, and basic quiz programs.

Tonight I was working on code that would parse an Apache configuration file and only display the DocumentRoot.

Parse Apache Configuration for DocumentRoot

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

#define MAXLINE 128

FILE *file;

int main(int argc, char *argv[])  
{

    int i,x;  
    char line[MAXLINE];  
    char * temp;

    if (argc == 1)  
    {  
        puts("You must enter a file/files to search.");  
        exit(1);  
    }

    for (i=1; i<argc;i++)  
    {  
        file = fopen(argv[i], "r");

        if (file == NULL)  
        {  
            puts("Could'nt open file");  
            exit(1);  
        }

        while ( (fgets(line, MAXLINE, file)) != NULL)  
        {  
            temp = malloc(sizeof (char) * 128);

            for (i=0; i<MAXLINE; i++)  
            {  
                do   
                {  
                    temp[i] = line[i];  
                    i++;  
                } while (line[i] != '\n');  
                temp[i] = '\0';  
                break;  
            }

            if (strstr(temp, "DocumentRoot") != NULL) {  
                printf("%u\n", temp);  
            }

            free(temp);  
        }  
    }  
}