simply web server by unix c program
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/wait.h>
#define QLEN 20
#define APPLY_HEAD "HTTP/1.1 200 OK\r\nContent-Type: "
#define IMG "image/jpg"
#define TEXT "text/html"
#define APPLY_END "\r\n\r\n"
typedef struct
{
in_port_t port;
char root[1024];
} cnf_t;
void err_sys (char *str) { perror (str); exit (1); }
cnf_t * config (cnf_t * arg)
{
FILE *fp;
char buf[1024];
char *p;
static cnf_t backup;
if (NULL == arg)
arg = &backup;
fp = fopen ("config.ini", "r");
if (fp == NULL)
err_sys ("fail to fopen");
fgets (buf, 1024, fp);
p = strstr (buf, "=");
arg->port = atoi (p + 1);
fgets (buf, 1024, fp);
p = strstr (buf, "=");
strcpy (arg->root, p + 1);
arg->root[strlen (arg->root) - 1] = '\0';
fclose (fp);
return arg;
}
int socket_init (in_port_t port)
{
int lfd, n;
struct sockaddr_in serv_addr;
lfd = socket (AF_INET, SOCK_STREAM, 0);
if (lfd == -1)
err_sys ("fail to socket");
bzero (&serv_addr, sizeof (serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons (port);
inet_pton (AF_INET, "192.168.0.18", &serv_addr.sin_addr.s_addr);
n = bind (lfd, (struct sockaddr *) &serv_addr, sizeof (serv_addr));
if (n == -1)
err_sys ("fail to bind");
n = listen (lfd, QLEN);
if (n == -1)
err_sys ("fail to listen");
return lfd;
}
char *get_path(int cfd, const char *root)
{
char *path; int n;
char *p, *q, *filename;
char buf[1024];
path = (char *)malloc(sizeof(char) * 1024); //or static char path[1024];
if (NULL == path) err_sys("fail to malloc ");
n = read (cfd, buf, 1024);
buf[n]
相关文档:
可惜MS-DOS不是中国人写的,不支持中文。
/* Note:Your choice is C IDE */
#include "stdio.h"
main(int argc, char *argv[])
{
FILE *fp;
char ch;
int num=0,max;
int line=0;
if((fp=fopen(argv[1],"rt"))==NULL)
{
printf("\nCannot open file strike any key exit!");
getch();
exit(1);
......
1. 什么是空指针常量(null pointer constant)?
[ 6.3.2.3-3] An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.
这里告诉我们:0、0L、'\0'、3 - 3、0 * 17 (它们都是“integer constant expression”)以及 ......