C言語でCGI

○サンプル2

整数をいれて下さい。
加・減算する整数をいれて下さい。
+ - * /

(ソースを貼り付けています。タグ等、一部正しく表示されない部分があります。)
/********************************************************************

	CGI Program by C Language

	Composed by N.Tsuda ( ntsuda@anet.ne.jp )	Nov/2001

********************************************************************/

#include 
#include 
#include 

int main()
{
	int	length;
	char	*query;

	int data[20];
	char szInData[1024];
	char *psInData;
	char szDataArea[3][256];
	char szDataAreaName[3][256];
	char szCommand[32];

	int command;
	char chcommand;
	float result,fa,fb;

	/* In case Request is "GET" */
	if( strcmp(getenv("REQUEST_METHOD"),"GET") == 0 ) 
	{
		length = strlen(getenv("QUERY_STRING"));
		query = (char *)malloc( length );
		strcpy(query,getenv("QUERY_STRING"));
	}
	else
	{
		/* In case Request is "POST" */
		length = atoi(getenv("CONTENT_LENGTH"));
		query = (char *)malloc( length );
		scanf("%s",query);
	}

	/***  ***/
	if( getenv( "QUERY_STRING" )!=NULL )
	{
		strcpy( szInData, getenv( "QUERY_STRING" ) );
	}
	else
	{
		strcpy( szInData, "No Input" );
	}

	/*** Separate Data ***/
	strcpy( szDataAreaName[0], strtok( szInData, "=" ) );
	strcpy( szDataArea[0], 	   strtok( NULL, "&" ) );
	strcpy( szDataAreaName[1], strtok( NULL, "=" ) );
	strcpy( szDataArea[1], 	   strtok( NULL, "&" ) );
	strcpy( szDataAreaName[2], strtok( NULL, "=" ) );
	strcpy( szCommand,     strtok( NULL, "&" ) );

	/*** Character -> Number ***/
	fa = atof( szDataArea[0] );
	fb = atof( szDataArea[1] );
	command = atoi( szCommand );

	/*** Command ***/
	switch ( command )
	{
		case 1:
			result = fa + fb;
			chcommand = '+';
			break;
		case 2:
			result = fa - fb;
			chcommand = '-';
			break;
		case 3:
			result = fa * fb;
			chcommand = '*';
			break;
		case 4:
			result = fa / fb;
			chcommand = '/';
			break;
		defalut:
			break;
	}

	/*** HTML Write ***/
	printf("Content-type: text/html\n\n");
	printf("QUERY\n");
	printf("Input is =[%s]\n
",query); // printf( "Value1 = [%s] Value2 = [%s]\n
", szDataAreaName[0], szDataArea[0] ); printf( "%f %c %f = [%f]\n
", fa, chcommand, fb,result ); printf( "\n" ); }

ダウンロード


これをコンパイルして、実行ファイルをcgi-binなど、CGI実行可能ディレクトリに移動する。
たとえば、"/home/httpd/cgi-bin/"。
ここにhtmlファイルからリンクを張ればよい。


Return