Register
It is currently Thu Jul 24, 2014 1:18 pm

Script for writing a C program


All times are UTC - 6 hours


Post new topic Reply to topic  [ 1 post ] 
Author Message
 PostPosted: Fri Mar 12, 2010 8:30 am   

Joined: Tue Mar 02, 2010 9:55 pm
Posts: 24
Location: Canada
Copied from iesaya idea's(script for writing scripts) but for a simple 'Hello, World!' C program..

Note: the gcc compiler requires the source code file name to have an extension .c

Code:
#! /bin/sh

echo -n "enter filename->"
read myfile

creatit()
{
   exec 3>>$1

   echo "#include <stdio.h>">&3
   echo "#include <stdlib.h>">&3
   echo >&3
   echo "int main(int argc, char**argv)">&3
   echo "{">&3
   echo "   fputs(\"Hello, World!\\n\", stdout);">&3
   echo "   exit(EXIT_SUCCESS);">&3
   echo "}">&3

   exec 3>&-

   mypos=`expr index $1 .`#get the position of .c from the filename
   mypos=`expr $mypos - 1`#so we can strip it out

   if gcc $1 -Wall -ansi -pedantic -o ${1::$mypos}>/dev/null 2>&1 \
      && echo -n "do you want to execute->(y/n)"
   then
      read ans
      if [ "$ans" = "y" ]
      then
         ./${1::$mypos}
      fi
   else
      echo "'$1' failed to compile"
      exit 1
   fi
}

if [ -f "$myfile" ]
then
   echo -n "'$myfile' already exists - overwrite->(y/n)"
   read ans

   if [ "$ans" = "y" ]
   then
      rm -f $myfile
      creatit $myfile
   else
      echo "exiting program"
      exit 1
   fi
else
   creatit $myfile
fi

exit 0


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 1 post ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 16 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP