Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

help required in c assignment

Posted on 1999-10-16
38
Medium Priority
?
254 Views
Last Modified: 2010-04-15
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.
0
Comment
Question by:marcel321
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 14
  • 10
  • 6
  • +4
38 Comments
 
LVL 84

Expert Comment

by:ozo
ID: 2133205
cc -Dprogram=int
0
 

Accepted Solution

by:
tantya earned 200 total points
ID: 2133408
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
 
LVL 6

Expert Comment

by:Triskelion
ID: 2133477
Lookup:
   strtok()
   FILE *
   fopen()
   EOF()
   fgets()
   fclose()
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:marcel321
ID: 2133570
what is the command that will identify whether the input file is a c or pascal
program.i am a little confused.
0
 
LVL 6

Expert Comment

by:Triskelion
ID: 2133691
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
 

Author Comment

by:marcel321
ID: 2133699
should include or begin be used to identify whether the input file is a c or pascal
program.
0
 
LVL 6

Expert Comment

by:Triskelion
ID: 2133712
#include is C
BEGIN is pascal
0
 
LVL 6

Expert Comment

by:Triskelion
ID: 2133979
Do you know where to start?
0
 

Author Comment

by:marcel321
ID: 2134622
no i don't .i need to know how to start.
0
 
LVL 84

Expert Comment

by:ozo
ID: 2134656
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
 
LVL 6

Expert Comment

by:Triskelion
ID: 2134681
Also...
How much time do you have?
0
 
LVL 3

Expert Comment

by:mliberi
ID: 2135048
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
 
LVL 84

Expert Comment

by:ozo
ID: 2135128
Can a C program start with
(*
0
 
LVL 5

Expert Comment

by:scrapdog
ID: 2135352
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
 

Author Comment

by:marcel321
ID: 2135459
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
 
LVL 1

Expert Comment

by:Lab_Rat
ID: 2135755
ozo - #DEFINE ???
0
 
LVL 1

Expert Comment

by:Lab_Rat
ID: 2135764
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
 

Author Comment

by:marcel321
ID: 2137598
ok so how do i begin
0
 
LVL 84

Expert Comment

by:ozo
ID: 2137739
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
 
LVL 3

Expert Comment

by:mliberi
ID: 2137844
>> 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
 
LVL 84

Expert Comment

by:ozo
ID: 2138186
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
 
LVL 6

Expert Comment

by:Triskelion
ID: 2147407
/*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
 
LVL 6

Expert Comment

by:Triskelion
ID: 2147414
Correction, that last "argc" should be "argv".
0
 

Author Comment

by:marcel321
ID: 2151397
can u explain what the program does .where do i need to add the
input file to be checked.
0
 
LVL 6

Expert Comment

by:Triskelion
ID: 2151405
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
 

Author Comment

by:marcel321
ID: 2153701
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
 
LVL 6

Expert Comment

by:Triskelion
ID: 2156307
I see what you're trying to do, and you're working too hard.

Look up
   strtok()
0
 
LVL 6

Expert Comment

by:Triskelion
ID: 2157447
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
 
LVL 84

Expert Comment

by:ozo
ID: 2157472
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
 

Author Comment

by:marcel321
ID: 2157738
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
 
LVL 6

Expert Comment

by:Triskelion
ID: 2157826
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
 
LVL 3

Expert Comment

by:mliberi
ID: 2158411
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
 
LVL 6

Expert Comment

by:Triskelion
ID: 2159077
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
 

Author Comment

by:marcel321
ID: 2161322
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
 
LVL 5

Expert Comment

by:scrapdog
ID: 2161415
>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
 
LVL 6

Expert Comment

by:Triskelion
ID: 2162979
Did my last code snippet help any?
0
 

Author Comment

by:marcel321
ID: 2163239
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
 
LVL 6

Expert Comment

by:Triskelion
ID: 2186259
#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

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.

722 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question