Using C for CGI Programming
At runtime, I need to be able to configure the database connection. Given a filename and an array of character strings for the configuration keys, my configuration function populates a corresponding array of configuration values, as shown in Listing 2. Now I can populate a string array with whatever keys I've chosen to use and get the results back in the value array.
Listing 2. Runtime Configuration Function
void config_read(char* filename, char** key,
char** value) {
FILE* cfile;
char tok[80];
char line[2048];
char* target;
int i;
int length;
cfile = fopen(filename, "r");
if (!cfile) {
perror("config_read");
return;
}
while(fgets(line, 2048, cfile)) {
if ((target = strchr(line, '='))) {
sscanf(line, "%80s", tok);
for(i=0; key[i]; i++) {
if (strcmp(key[i], tok) == 0) {
target++;
while(isspace(*target)) target++;
length = strlen(target);
value[i] = (char*)calloc(1, length + 1);
strcpy(value[i], target);
target = &value[i][length - 1];
while(isspace(*target)) *target-- = 0;
}
}
}
}
fclose(cfile);
}
The user interface has two parts. As a programmer, I'm concerned primarily with the input forms and URL strings. Everybody else cares how the page around my form looks and takes the form itself for granted. The solution to keep both parties happy is to have the page exist separately from the form and my program.
Templating libraries abound in PHP and Perl, but there are no common HTML templating libraries in C. The easiest solution is to include only the barest minimum of the output in my C code and keep the rest in HTML files that are output at the appropriate time. A function that can do this is found in Listing 3.
Listing 3. HTML Template Function
void html_get(char* path, char* file) {
struct stat sb;
FILE* html;
char* buffer;
char fullpath[1024];
/* File & path name exceed system limits */
if (strlen(path) + strlen(file) > 1024) return;
sprintf(fullpath, "%s/%s", path, file);
if (stat(fullpath, &sb)) return;
buffer = (char*)calloc(1, sb.st_size + 1);
if (!buffer) return;
html = fopen(fullpath, "r");
fread((void*)buffer, 1, sb.st_size, html);
fclose(html);
puts(buffer);
free(buffer);
}
Before generating output, I need to tell the Web server and the browser what I'm sending; cgiHeaderContentType() accomplishes this task. I want a content type of text/html, so I pass that as the argument. The general steps to follow for any page I want to display are:
cgiHeaderContentType("text/html");
html_get(path, pagetop.html);
Generate the program content.
html_get(path, pagebottom.html);
Now that I can generate a page and print a form, I need to be able to process that form. I need to read both numeric and text elements, so I use a couple of functions from the cgic library: cgiFormStringNoNewlines() and cgiFormInteger(). The cgic library implements the main function and requires that I implement int cgiMain(void). cgiMain() is where I put the bulk of my form processing.
To display a single record in my show_event function, I get the event_no (my primary key) from the CGI eventno parameter. cgiFormInteger() retrieves an integer value and sets a default value if no CGI parameter is provided.
I also need to get a whole raft of data from the form in save_event. Dates are thorny things to input because they consist of three pieces of data: year, month and date. I need both a begin and an end date, which gives me six fields to interpret. I also need to input the name of the event, begin and end times (which are strings because they might be events themselves, such as sunrise or sunset) and the location. Listing 4 shows how this works in code.
Listing 4 also demonstrates cgiHeaderLocation(), a function that redirects the user to a new page. After I've saved the submitted data, I want to show the event listing page. Instead of a literal string, I use one of the variables that libcgic provides, cgiScriptName. Using this variable instead of a literal one means the program name can be changed without breaking the program.
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
| Dart: a New Web Programming Experience | May 07, 2013 |
- RSS Feeds
- New Products
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- Home, My Backup Data Center
- New Products
- Developer Poll
- Trying to Tame the Tablet
- Paranoid Penguin - Building a Secure Squid Web Proxy, Part IV
- mini tablet compare
6 min 7 sec ago - Looking Good
3 hours 39 min ago - Hey God - You may not be
7 hours 52 min ago - Reply to comment | Linux Journal
10 hours 25 min ago - Drupal is an Awesome CMS and a Crappy development framework
15 hours 4 min ago - IT industry leaders
17 hours 27 min ago - Reply to comment | Linux Journal
1 day 10 hours ago - Reply to comment | Linux Journal
1 day 12 hours ago - Reply to comment | Linux Journal
1 day 14 hours ago - great post
1 day 14 hours ago
Enter to Win an Adafruit Prototyping Pi Plate Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Prototyping Pi Plate Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- Next winner announced on 5-21-13!
Free Webinar: Linux Backup and Recovery
Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.
In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.




Comments
source code url broken
Thanks for you cool post. I'm trying to develop rest service by c/cgi, could you fix the broken url and make your source code and makefile available?