• C

help required in c assignment

i am a beginner & i don't know where to start.so pls help me.i need to write a program in C whose input is a file
containing a program in C or pascal.the program should
output the language i.e. C or pascal of the program in the
input file.
i need help on how to go about it.
marcel321Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ozoCommented:
cc -Dprogram=int
0
tantyaCommented:
Skeleton of C prog.


/* <statements> */ ---- commet , not compiled by compiler



#include <stdio.h>

main()
{
        printf("\n\aHello World ......\a\n");
}


to see the help go on that word and press CRTL-F1
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
TriskelionCommented:
Lookup:
   strtok()
   FILE *
   fopen()
   EOF()
   fgets()
   fclose()
0
The Ultimate Tool Kit for Technolgy Solution Provi

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy for valuable how-to assets including sample agreements, checklists, flowcharts, and more!

marcel321Author Commented:
what is the command that will identify whether the input file is a c or pascal
program.i am a little confused.
0
TriskelionCommented:
There is no single command you can use to tell the difference.

You will have to look for certain keywords.
You can look for the ".c" or ".pas" extension
You can look to see if the word PROGRAM appears near the top of the file (pascal).
You can look for "#include" (.c)

There are certain things that event the most bare-boned language files will have. In C, it is the function main()
But it can be
   int main(int argc, char **argv)
   main(int argc, char **argv)
   void main(int argc, char **argv)
   int main(void)
   void main(void)
   int main()
   void main()
   main()

In pascal, you will always have a "BEGIN" and an "END."

Of course (to confuse things) this only works if you're dealing with main modules and not just function modules or Turbo Pascal Units

Look at this C example

void main(void)
{
   printf("Triskelion was here.");
}

and this pascal example

BEGIN
   WRITE('Triskelion was here.');
END.


What would you use to check for differences?
0
marcel321Author Commented:
should include or begin be used to identify whether the input file is a c or pascal
program.
0
TriskelionCommented:
#include is C
BEGIN is pascal
0
TriskelionCommented:
Do you know where to start?
0
marcel321Author Commented:
no i don't .i need to know how to start.
0
ozoCommented:
Could you look at a file and decide whether it was a C or Pascal program?
Could you decribe to another person how to do it?
0
TriskelionCommented:
Also...
How much time do you have?
0
mliberiCommented:
The reply can't be simple, you need a syntax parser.
Basing your 'solution' on simply searching some 'keywords'
may lead to errors.
Why not using the parser of your preferite C or PASCAL compiler? You must only try to compile your file. If the compiler complains the file doesn't contain a valid C or PASCAL program.

Is the following a C program?

(*
main()
{
  printf("hello world\n");
}
*)

BEGIN
  Writeln('hello world')
END.
0
ozoCommented:
Can a C program start with
(*
0
scrapdogCommented:
It is possible for a valid pascal file (in some implementations) to not contain PROGRAM or BEGIN.

Here are some ways to check if it is pascal:

1.  If the first word in the file is UNIT, followed by an identifier, followed by a semicolon, it is most likely pascal.

2.  If it does not contain UNIT, then if it is a valid pascal file it is guaranteed to contain at least
one "begin" and exactly one "end."

ALL pascal files have an "end.", usually at the end of the file (what follows it is meaningless).
0
marcel321Author Commented:
i can tell the difference between a c & pascal program
i hv about 2 weeks.
the program starting with " (* " doesn't work.
if i need to use a syntax parser then how.

 
0
Lab_RatCommented:
ozo - #DEFINE ???
0
Lab_RatCommented:
Maybe:

#define (* /*
#define )* */

(*

All of this program will work!!//

Void mainly(void)
[
PRINT AT 7,8;BRIGHT 1;FLASH 1; INK 2; PAPER 1;"Hello World!"
]

)*

You will find this program compiles.
0
marcel321Author Commented:
ok so how do i begin
0
ozoCommented:
You might start by thinking about how you would decide whether a file contained a program in C or Pascal.
If you're not sure how to do it in all cases, see if there are any simple cases where you can decide.
You might try to practice writing a program that works in at least some cases,
perhaps in the process you might learn things that will help you when you're ready to understan the full problem.
0
mliberiCommented:
>> ozo: Can a C program start with (* ?

No. In fact the program I wrote is a PASCAL well formed string.

Using the embedded syntax parser of compilers is very simple, you can simply TRY to compile the program. The compiler complains (and return an error code) if the input file doesn't contain a well formed string.

Example (ksh):


if cc -c my_file.boh 2>/dev/null
  then
    echo my_file.boh is a C program
    rm -f my_file.o
  else
    if pas my_file.boh 2>/dev/null
      then
        echo my_file.boh is a PASCAL program
        rm -f my_file   # my_file.exe in dos/win environment
      else
        echo my_file.boh is neither C neither PASCAL
    fi
fi
0
ozoCommented:
cc may complain about an input file containing

#include "myprog.h"

or

#abort

even if it was a perfectly valid C program, and not a valid pascal program.
0
TriskelionCommented:
/*first clue*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef enum {FALSE, TRUE} BOOL;
#define      NUM_LANGUAGES      2
#define      MAX_KEYWORDS      7

/**********************************************
** Structure the static data for easy lookup **
**********************************************/
enum {eCLANG, ePASCAL, eUNKNOWN} ENUM_LANGUAGES;
static      struct      tagLANGUAGES
            {
            int            intValue;
            char      *      ptrStringName;
            char       *      ptrArrStrKeywords[MAX_KEYWORDS];
            }      xarLanguages[] =
            {
            {eCLANG,            "C",                  {"#incude", "void", "int", "main", "argc", "argc", 0}},
            {ePASCAL,      "Pascal",      {"PROGRAM", "UNIT", "BEGIN", "END", "VAR", "TYPE", 0}},
            {eUNKNOWN,      "Unknown",      {0}}
            };
            
/************************
** Function prototypes **
************************/
void      main(int argc, char ** argv);
int      CheckForLanguage(char * ptrLangString);/* function to check for C or PASCAL */
BOOL      IsOneOf(char * strToken, char ** ptrStringArray);
0
TriskelionCommented:
Correction, that last "argc" should be "argv".
0
marcel321Author Commented:
can u explain what the program does .where do i need to add the
input file to be checked.
0
TriskelionCommented:
All I gave here were the function prototypes and the structure and the defines.

You would need to add the "main" and "IsOneOf" and "CheckForLanguage" fuctions.


You will need to open the input file
Check it for content.
Print your findings.
0
marcel321Author Commented:
this is my version of the program,but i am not getting the desired
output .also this only opens a c program .i need to check for c &
pascal.pls advice.i am open to suggestions.


#include <stdio.h>
#include <string.h>
#inlcude <conio.h>
#include <stdlib.h>
char remaining_char[200];
char *position1,Comment_Found;
main ()
{
 FILE *fp1;
 char string1[6][5]={"include","main","/*","/*","->","#"};
 char string2[6][1]={"/","*","#","-",">"};
 char next_char[200];
 clrscr();
 if (fp1=fopen("hello.c","r"))
{
   while ((fgets(next_char,200,fp1)) !=EOF)

  {
    printf ("%s\n",next__char);
   Comment_Found='N';
   strcpy (remaining_cchar,NULL);
   position1=strstr(next_char,"*/");
   printf ("%s \t %s",position1,next__char);
   if (position1==(char *)NULL)
      {
        printf ("comment not found in C \n");
       position1=strstr(next_char,"{");
       printf ("----%s----- \t %s",position1,next_char);
       if (position==NULL)
        {
          printf ("comment not found in pascal\n");
        }
        else
        {
         strcat (remaining char,position1);
         printf ("remaining string of pascal %s",remaining_char);
         Comment_Found='P';
        }
}
else
     if ((Comment_Found=='N'))
       {
         strcat (remaining_char,position1);
         printf ("remaining string %s \n",remaining_char);
         Comment_Found='C';
         getch ();
       }
     strcpy (remaining_char,remaining_char);
     getch ();
}
fclose(fp1);
printf ("\n");
getch();
}
/* End of Program */
 

 
0
TriskelionCommented:
I see what you're trying to do, and you're working too hard.

Look up
   strtok()
0
TriskelionCommented:
Remember, you don't have to disect the string completely, let strtok() do it.

/*Here is another piece of the puzzle*/

/************************
** Function prototypes **
************************/
void      main(int argc, char ** argv);
int      CheckForLanguage(char * ptrLangString);/* function to check for C or PASCAL */
BOOL      IsOneOf(char * strToken, char ** ptrStringArray);

/*****************************************************************
** main                                                         **
** This function tests for the input file, scans through it and **
** attempts to determine the language.  This function calls two **
** other functions to determine the language (C or PASCAL)      **
*****************************************************************/
void main(int argc, char ** argv)
{                                               /***************************/
      auto            FILE      *      hanInputFile=NULL;                /* handle of input file    */
      static      char            strLangFile[FILENAME_MAX]; /* string to hold filename */
      static      char            strData[255];                     /* input from file         */
      auto            int            intLang=0;                 /* value for found language*/
                                                   /***************************/
      if (argc<2)
            {
            printf("Please enter the name of a file to test for its language.");
            exit(1);
            }

      strncpy(strLangFile, argv[argc-1], sizeof(strLangFile));
      printf("Checking (%s)...\r\n", strLangFile);

      if (NULL==(hanInputFile=fopen(strLangFile, "rb")))
            {
            printf("The file %s cannot be found.\r\n", strLangFile);
            exit(2);
            }

      while(!feof(hanInputFile))
            {
            fgets(strData, sizeof(strData), hanInputFile);
            if (eUNKNOWN>(intLang=CheckForLanguage(strData)))
                  {
                  break;
                  }
            }
      printf("Language is %s", xarLanguages[intLang].ptrStringName);
      fclose(hanInputFile);
}
0
ozoCommented:
Pascal  keywords can appear in C programs, and C keywords can appear in Pascal programs,
The middle of the file could become completely ambiguous due to mutual commenting.
Given that you know the input is a file containing a program in C or pascal. it should suffice to check whether the file starts like a legal  c or pascal program.
0
marcel321Author Commented:
In place of which command should i use strtok & how .
Is my program in the right direction.
What all functions do i need to add in ur program to make it fully working.
Is the latest function prototype a modifiation or an addition of the
previous one.
thanx.
0
TriskelionCommented:
You're on the right track.  The strtok() function would replace most of the string manipulation function calls that are piecing strings together to see what they are.

List out the things you need to do in logical order.

Open the target file
While not end of file
   Loop through the file looking for keywords.
   When the first good keyword is found STOP
   If EOF is encountered, STOP

Display the language found if any
0
mliberiCommented:
I don't understand why you discuss implementation details without, first of all, outlining a logic behind.

I say that looking for specific tokens is a poor technique and may lead to errors.

A little improvement could be looking for specific tokens OUTSIDE comment blocks.

Anyway the best solution is to use (or build with lex/yacc) a syntax parser. It's not easy, I know.

'indent', the gnu C sources formatter utility, has an embedded parser and the sources are free downloadable. You can work on it.

Another useful program, I think could be 'p2c' (pascal to C converter)

Good luck!
0
TriskelionCommented:
Marcel, do you know how complex your input data will be?

Will it be bare-boned C and PASCAL or can it be any type and style of either language?

I'm assuming this is for a school assignment.  My comments are based on this being a "one-timer" and not something you will use in your arsenal of code.
0
marcel321Author Commented:
i am using a simple program for input file such as hello world.
it will avoid getting into a lot of complications & this a one timer.  
0
scrapdogCommented:
>Another useful program, I think could
>be 'p2c' (pascal to C converter)

I have never seen a 'c2p' anywhere yet...I would like one of those. =)

0
TriskelionCommented:
Did my last code snippet help any?
0
marcel321Author Commented:
i thought i'd write the program in a different way .is it ok.


#include <stdio.h>
#include <string.h>

void main(void)
{
      char filename[15];  /*      Name of the input file                        */
      char cur_char;        /*      The character currently read                   */
      char char_set[15];  /*  A set of characters read from the file    */
      char isPascal='n';  /*  Flag to store whether program is C or Pascal.*/

      FILE *fp;

      fflush(stdin);

      /*      Accepting the name of the program File                        */

      printf("Enter the name of the file to be tested : ");
      gets(filename);
      fflush(stdin);

      /*      Opening the file for reading                              */

      if ((fp = fopen(filename, "r")) != NULL)
      {

            /*      Reading a character                                       */

            while ((cur_char = fgetc(fp)) != EOF)
            {
                  /*    Removing initial white spaces                        */

                  if (cur_char == ' ' || cur_char == '\t'
                   || cur_char == '\n')
                        continue;

                  /*    Removing Initial Comments, Pascal style, if any      */

                  if (cur_char == '{')
                  {
                        while ((cur_char = fgetc(fp)) != EOF
                                 && cur_char != '}');
                        if (cur_char != EOF)
                              continue;
                        else
                              break;
                  }


                   if (cur_char == '(' &&
                        (cur_char = fgetc(fp)) != EOF &&
                         cur_char == '*')
                  {
                        do
                        {
                              fgets(char_set, 3, fp);

                              /*      Moving back one character             */

                              fseek(fp, -1, SEEK_CUR);
                        } while (strcmp(char_set, "*)") != 0);
                        cur_char = char_set[1];
                        if (cur_char != EOF)
                              continue;
                        else
                              break;
                  }
                  else
                        fseek(fp, -1, SEEK_CUR);

                  /*  Now, the first word should be "Program" in case of
                      a Pascal Program, and something else in case of a
                      C Program.                                          */

                  fgets(char_set, 9, fp);
                  if (stricmp(char_set, "Program ") == 0)
                  {
                        /*  Testing whether it is followed by a program-id,
                            and not anything else.                        */

                        /*      First removing any white spaces and comments */

                        while ((cur_char = fgetc(fp)) != EOF)
                        {
                              /*    Removing white spaces                  */

                              if (cur_char == ' ' || cur_char == '\t'
                                    || cur_char == '\n')
                                    continue;

                              /*    Removing Comments                        */

                              if (cur_char == '{')
                              {
                                    while ((cur_char = fgetc(fp)) != EOF
                                       && cur_char != '}');
                                    if (cur_char != EOF)
                                          continue;
                                    else
                                          break;
                              }


                               if (cur_char == '(' &&
                                    (cur_char = fgetc(fp)) != EOF &&
                                     cur_char == '*')
                              {
                                    do
                                    {
                                          fgets(char_set, 3, fp);

                                          /*      Moving back one character  */

                                          fseek(fp, -1, SEEK_CUR);
                                    } while (strcmp(char_set, "*)") != 0);
                                    cur_char = char_set[1];
                                    if (cur_char != EOF)
                                          continue;
                                    else
                                          break;
                              }
                              else
                                    fseek(fp, -1, SEEK_CUR);

                              if(isalpha((cur_char = fgetc(fp))) ||
                                    cur_char == '_')
                              {
printf("%s is a Pascal Program.",
  filename);
                                    isPascal = 'y';
                              }
                              break;
                        }
                  }
                  break;
            }
            if (isPascal == 'n')
                  printf("%s is a C Program.", filename);

            /*      Closing the File                                           */

            fclose(fp);
      }
      else
            printf("Can't Open file %s.", filename);
}

 
0
TriskelionCommented:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef enum {FALSE, TRUE} BOOL;
#define      NUM_LANGUAGES      2
#define      MAX_KEYWORDS      7

/**********************************************
** Structure the static data for easy lookup **
**********************************************/
enum {eCLANG, ePASCAL, eUNKNOWN} ENUM_LANGUAGES;
static      struct      tagLANGUAGES
            {
            int            intValue;
            char      *      ptrStringName;
            char       *      ptrArrStrKeywords[MAX_KEYWORDS];
            }      xarLanguages[] =
            {
            {eCLANG,            "C",                  {"#incude", "void", "int", "main", "argc", "argc", 0}},
            {ePASCAL,      "Pascal",      {"PROGRAM", "UNIT", "BEGIN", "END", "VAR", "TYPE", 0}},
            {eUNKNOWN,      "Unknown",      {0}}
            };
            
/************************
** Function prototypes **
************************/
int      main(int argc, char ** argv);
int      CheckForLanguage(char * ptrLangString);/* function to check for C or PASCAL */
BOOL      IsOneOf(char * strToken, char ** ptrStringArray);

/*****************************************************************
** main                                                         **
** This function tests for the input file, scans through it and **
** attempts to determine the language.  This function calls two **
** other functions to determine the language (C or PASCAL)      **
*****************************************************************/
int      main(int argc, char ** argv)
{                                               /***************************/
      auto            FILE      *      hanInputFile=NULL;                /* handle of input file    */
      static      char            strLangFile[FILENAME_MAX]; /* string to hold filename */
      static      char            strData[255];                     /* input from file         */
      auto            int            intLang=0;                 /* value for found language*/
                                                   /***************************/

      if (argc<2)
            {
            puts("Please enter the name of a file to test for its language.");
            return      1;
            }
            
      strncpy(strLangFile, argv[argc-1], sizeof(strLangFile));
      printf("Checking (%s)...\r\n", strLangFile);
      
      if (NULL==(hanInputFile=fopen(strLangFile, "rb")))
            {
            printf("The file %s cannot be found.\r\n", strLangFile);
            return      2;
            }
      
      while(!feof(hanInputFile))
            {
            fgets(strData, sizeof(strData), hanInputFile);
            if (eUNKNOWN>(intLang=CheckForLanguage(strData)))
                  {
                  break;
                  }
            }
      printf("Language is %s\r\n", xarLanguages[intLang].ptrStringName);
      fclose(hanInputFile);
      return      0;
}

/******************************************************************************
** IsOneOf --                                                                **
** This function compares a string with an array of strings and returns      **
** TRUE if the string is found in the array of strings.                      **
******************************************************************************/
BOOL IsOneOf(char * strToken, char ** ptrStringArray)
{
      static      BOOL      blnFound=FALSE;
      auto            int      intLoop=0;
      
      for (intLoop=0; ptrStringArray[intLoop]; intLoop++)
            {
            if (!strcmp(strToken, ptrStringArray[intLoop]))
                  {
                  blnFound=TRUE;
                  break;
                  }
            }
      return      blnFound;
}

/******************************************************************************
** CheckForLanguage --                                                       **
** This function checks to see if the given line is PASCAL or C              **
** This function will continue to return 0 until it can determine the lang.  **
** If the string is a line of PASCAL, it will return 2 or 1 for C            **
******************************************************************************/
int      CheckForLanguage(char * ptrLangString)
{
      auto            char      *      ptrStringToken;
      static      char      *      ptrStringSeps=" \n\r,\t();=-+";
      static      int            intReturn=eUNKNOWN;
      auto            int            intLoop=0;
      auto            int            intLoop2=0;
      
      ptrStringToken=strtok(ptrLangString, ptrStringSeps);
      while(ptrStringToken)
            {
            for (intLoop=0;(intLoop<NUM_LANGUAGES) && intReturn==eUNKNOWN; intLoop++)
                  {
                  if (IsOneOf(ptrStringToken, xarLanguages[intLoop].ptrArrStrKeywords))
                        {
                        intReturn=intLoop;
                        break;
                        }
                  }
            ptrStringToken=strtok(NULL, ptrStringSeps);
            }
      return intReturn;
}
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.