Solved

Help Convert C to Pascal

Posted on 2009-04-09
16
249 Views
Last Modified: 2012-05-06
Can someone help me to convert this small program to delphi ?

http://www.let.rug.nl/~kleiweg/postscript/pssplit.c
0
Comment
Question by:pucko
[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
  • 7
  • 5
  • 2
  • +1
16 Comments
 
LVL 8

Expert Comment

by:BdLm
ID: 24108088
0
 
LVL 8

Expert Comment

by:BdLm
ID: 24108354

here is a sample translation , using www.torry.net translation tools
unit test_c_txt;
{*************************************************************************
 
->	Converted with C to Pascal Converter 1.0
->	Release: 1.5.11.2008
->	Email: al_gun@ncable.net.au
->	Updates: http://cc.codegear.com/Author/302259
->	Copyright © 2005-2008 Ural Gunaydin, All rights reserved.
 
*************************************************************************}
 
interface
 
uses
	Windows, Messages, SysUtils, Classes;
 
(*
 * cFile: pssplit.c
 *
 * (c) Peter Kleiweg 1998
 *
 *  This is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as
 *  published by the Free Software Foundation; either version 2,
 *  or (at your option) any later version.
 *
 *)
 
//include <stdarg.h>
//include <stdio.h>
//include <stdlib.h>
//include <cString.h>
//include <errno.h>
 
{$ifdef __MSDOS__}
const strcasecmp(A, = B) (stricmp(A, B));
{$endif}
 
const BUFSIZE = 2048;
 
Char
    buffer [BUFSIZE + 1],
    *programname;
 
v1: procedure;
    syntax (),
    errit (Char const *format, Args: array of const);
 
function main (argc: integer; : Parray of argv): integer;
begin 
    cFile
        *fp;
    integer
        page = 0,
        prpage = 0,
        doclevel = 0,
        trailer = 0,
        even = 0,
        odd = 0,
        beginpage,
        endpage,
        retval := 1;
 
    programname := argv [0];
 
    if (argc <> 5) then 
        syntax ();
 
    beginpage := StrToInt (argv [2]);
    endpage := StrToInt (argv [3]);
    if (beginpage < 1 or endpage < beginpage) then 
        syntax ();
 
    if ( not  strcasecmp (argv [4], 'all')) then  begin 
        even := 1;
        odd := 1;
     end; else if ( not  strcasecmp (argv [4], 'even')) then 
        even := 1;
    else if ( not  strcasecmp (argv [4], 'odd')) then 
        odd := 1;
    else
        syntax ();
 
    fp := FileOpen (argv [1], 'r');
    if ( not  fp) then 
	errit ('Opening cFile ' mod s':  mod s', argv [1], strerror (errno));
 
    while (fgets (buffer, BUFSIZE, fp)) begin 
        if ( not  CompareMem (buffer, ' mod  mod Page:', 7)) then  begin 
            if ( not  doclevel) then  begin 
                page:= mod + 1;
                prpage = (
                    page >= beginpage and page <= endpage
                 and ((odd and (page mod 2)) or (even and not (page mod 2)))
                );
                if (prpage) then  begin 
                    retval := 0;
                    fputs (buffer, stderr);
                 end;
             end;
         end; else if ( not  CompareMem (buffer, ' mod  mod BeginDocument', 15)) then 
            doclevel:= mod + 1;
        else if ( not  CompareMem (buffer, ' mod  mod EndDocument', 13)) then 
            doclevel:= mod - 1;
        else if ( not  CompareMem (buffer, ' mod  mod Trailer', 9)) then  begin 
            if ( not  doclevel) then 
                trailer := 1;
         end;
 
	if ((page = 0) or prpage or trailer) then 
            fputs (buffer, stdout);
     end;
 
    FileClose (fp);
 
    if (retval) then 
        fprintf (stderr, ' mod s: No pages found', programname);
    
    result:= retval;
 end;
 
procedure errit (var format: const; v1: Args: array of const);
begin 
    va_list
	list;
 
    fprintf (stderr, 'Error  mod s: ', programname);
 
    va_start (list, format);
    vfprintf (stderr, format, list);
 
    fprintf (stderr, '');
 
    exit (2);
 end;
 
procedure syntax ();
begin 
    fprintf (
	stderr,
	'Usage:  mod s cFile.ps beginpage endpage all or even or odd'
	'Return value:'
	'0 - ok'
	'1 - no pages found'
	'2 - error',
	programname
    );
    exit (2);
 end;
 
implementation
 
end.

Open in new window

0
 
LVL 1

Author Comment

by:pucko
ID: 24108446
Still to much for me to get this to work
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!

 
LVL 1

Author Comment

by:pucko
ID: 24108481
the parts that I don't know what to replace with is for example:

    cFile
        *fp;
.....

 fp := FileOpen (argv [1], 'r');

and this part:


    fp := FileOpen (argv [1], 'r');
    if ( not  fp) then
	errit ('Opening cFile ' mod s':  mod s', argv [1], strerror (errno));
 
    while (fgets (buffer, BUFSIZE, fp)) begin
        if ( not  CompareMem (buffer, ' mod  mod Page:', 7)) then  begin
            if ( not  doclevel) then  begin
                page:= mod + 1;
                prpage = (
                    page >= beginpage and page <= endpage
                 and ((odd and (page mod 2)) or (even and not (page mod 2)))
                );
                if (prpage) then  begin
                    retval := 0;
                    fputs (buffer, stderr);
                 end;
             end;
         end; else if ( not  CompareMem (buffer, ' mod  mod BeginDocument', 15)) then
            doclevel:= mod + 1;
        else if ( not  CompareMem (buffer, ' mod  mod EndDocument', 13)) then
            doclevel:= mod - 1;
        else if ( not  CompareMem (buffer, ' mod  mod Trailer', 9)) then  begin
            if ( not  doclevel) then
                trailer := 1;
         end;
 
	if ((page = 0) or prpage or trailer) then
            fputs (buffer, stdout);
     end;
 
    FileClose (fp);
 
    if (retval) then
        fprintf (stderr, ' mod s: No pages found', programname);
 
    result:= retval;

Open in new window

0
 
LVL 8

Expert Comment

by:BdLm
ID: 24109248
var
    F: TextFile;
begin
    AssignFile(F, ReportFileName);
    ReWrite(F);

    writeln(f, 'your text ');


   closeFile(f);

end;
0
 
LVL 1

Author Comment

by:pucko
ID: 24109308
How to write a text to a file I still understand,  But not how to do the parsing with MemCompare etc.
0
 
LVL 6

Expert Comment

by:JosephGlosz
ID: 24109654
That sure is a piss-poor C-to-Pascal translation. I wonder how many syntax errors that has in it.  Looks to me like every single line has a syntax error. Multiple errors per line.  The translator couldn't even put semi-colons in the right places, and this is even a simple rule to implement: never put a semi-colon in front of an 'else.'

The translation didn't even compensate for C's ability to use integers as booleans directly. So it assigns 0 or 1 to "odd" and "even" (which are built in Delphi functions by the way) then uses them as booleans later. i.e.: if odd then blah blah.

the StdErr output wasn't even properly defined to write to "ErrOutput" and this should've been an easy conversion. Similar for fgets, fputs, fprintf etc.

So, if I get this right, BdLm's help was this: here's a file with a few pascal keywords in it and identifiers copied from the C file. Now, rewrite every line because it doesn't even approach being a working translation.




0
 
LVL 1

Author Comment

by:pucko
ID: 24109720
I agree.

Anyway, I think the right approach for me might be to use Ghostscript and the gsapi instead to extract the specified pages from a postscript file instead of converting this c code,

Unfortanly it seems like I only have two options there.
1.
   The problem there was that -dFirstPage= xx and -dLastPage=yy only works for a pdf  so my option there is to convert postscript to pdf, then extract the wanted pages into a new pdf and convert it back top postcript.

2. Extract to one postscript file per page with
the options -q -dBatch -dNOPAUSE-sDEVICE=pswrite -sOutputFile=c:\file.%003d.ps -f input.ps

Then through away the pages I don't want and then merge the wanted pages to a new ps file.

I think I will go for the first aproach and give up the idea of converting the c code. I guess ghostscript is more stable.
0
 
LVL 6

Expert Comment

by:JosephGlosz
ID: 24109899
Well, GhostScript is not inherently more stable; any software is only as stable as the developer makes it.  IMHO :)

I can't help with GhostScript in any way.  And converting even that small C program to Delphi looks to me - while very do-able - like an all-day task. With a healthy dose of debugging, because invariably there is some tiny detail that screws everything up.

If I had to do it for myself then I wouldn't mind spending all day on this. The C program actually looks somewhat simple: it just reads a file into memory (2K bytes at a time) and then looks for certain phrases ('Page:', 'EndDocument', 'Trailer', etc.) on certain 'pages.'  For some reason, being an odd or even page seems to matter.  

The 2048 byte buffer is probably there only because of 1998's memory limitations (costs).  Today, I don't think even disk cluster sizes are that small. So, I would probably modify the program to simply read in the entire file to memory, at once, and then scan through that looking for the targets.

Someone really proficient in C and Delphi might be able to whip this out in less time than a day though.  I just know that I couldn't

Good luck!
0
 
LVL 1

Author Comment

by:pucko
ID: 24109938
The ghostscript way is no problem for me. I currently use it for pdf conversion.
0
 
LVL 8

Expert Comment

by:BdLm
ID: 24112190
try #2 >  convert from  http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=331&lngWId=7
unit tesc;
 
interface
 
(*
 * File: pssplit.c
 *
 * (c) Peter Kleiweg 1998
 *
 *  This is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as
 *  published by the Free Software Foundation; either version 2,
 * ) or ((at your option) any later version.
 *
 *)
 
 
#ifdef __MSDOS__
#define strcasecmp(A, B) (strcomp(A, B))
#endif
 
#define BUFSIZE 2048
 
char
    buffer [BUFSIZE + 1],
    *programname;
 
procedure
    syntax (procedure),
    errit (char const *format, ...);
 
smallint main (smallint argc, char *argv [])
begin
    FILE
        *fp;
    smallint
        page := 0,
        prpage := 0,
        doclevel := 0,
        trailer := 0,
        even := 0,
        odd := 0,
        beginpage,
        endpage,
        retval := 1;
 
    programname := argv [0];
 
    if (argc <> 5)
        syntax ;
 
    beginpage := atoi (argv [2]);
    endpage := atoi (argv [3]);
    if (beginpage < 1 )) or (( endpage < beginpage)
        syntax ;
 
    if ( not  strcasecmp (argv [4], 'all')) then begin
        even := 1;
        odd := 1;
    end else if ( not  strcasecmp (argv [4], 'even'))
        even := 1;
    else if ( not  strcasecmp (argv [4], 'odd'))
        odd := 1;
    else
        syntax ;
 
    fp := fopen (argv [1], 'r');
    if ( not  fp)
  errit ('Opening file \'%s\': %s', argv [1], strerror (errno));
 
    while (fgets (buffer, BUFSIZE, fp)) then begin
        if ( not  memcmp (buffer, '%%Page:', 7)) then begin
            if ( not  doclevel) then begin
                page++;
                prpage := (
                    page >:= beginpage )) and (( page <:= endpage
                 )) and (( ((odd )) and (( (page % 2)) )) or (( (even )) and ((  not  (page % 2)))
                );
                if (prpage) then begin
                    retval := 0;
                    fputs (buffer, stderr);
                end
            end
        end else if ( not  memcmp (buffer, '%%BeginDocument', 15))
            doclevel++;
        else if ( not  memcmp (buffer, '%%EndDocument', 13))
            doclevel--;
        else if ( not  memcmp (buffer, '%%Trailer', 9)) then begin
            if ( not  doclevel)
                trailer := 1;
        end
 
  if ((page := 0) )) or (( prpage )) or (( trailer)
            fputs (buffer, stdout);
    end
 
    fclose (fp);
 
    if (retval)
        fprsmallintf (stderr, '\n%s: No pages found\n\n', programname);
    
    return retval;
end
 
procedure errit (char const *format, ...)
begin
    va_list
  list;
 
    fprsmallintf (stderr, '\nError %s: ', programname);
 
    va_start (list, format);
    vfprsmallintf (stderr, format, list);
 
    fprsmallintf (stderr, '\n\n');
 
    exit (2);
end
 
procedure syntax 
begin
    fprsmallintf (
  stderr,
  '\nUsage: %s file.ps beginpage endpage all|even|odd\n'
  'Return value:\n'
  '\t0 - ok\n'
  '\t1 - no pages found\n'
  '\t2 - error\n',
  programname
    );
    exit (2);
end

Open in new window

0
 
LVL 8

Expert Comment

by:BdLm
ID: 24112534
the best result by reading the pascal file is cad kas c2delphi.exe converter, not for free, you may translate and type the code by hand to the delphi ide
0
 
LVL 13

Accepted Solution

by:
ThievingSix earned 250 total points
ID: 24113583
Here is a hand conversion. I didn't do the error output stuff but this should get you started.
program Project2;
 
{$APPTYPE CONSOLE}
 
uses
  SysUtils,
  Windows;
 
const
  BUFSIZE = 2048;
 
var
  fp : DWORD;
  page : Integer = 0;
  prpage : Integer = 0;
  doclevel : Integer = 0;
  trailer : Integer = 0;
  even : Integer = 0;
  odd : Integer = 0;
  beginpage : Integer;
  endpage : Integer;
  retval : Integer = 1;
  programname : PChar;
  BytesRead : DWORD = 0;
  buffer : Array[0..BUFSIZE] of Char;
begin
  programname := PChar(ParamStr(0));
  If ParamCount <> 4 Then Exit;
  beginpage := StrToInt(ParamStr(2));
  endpage := StrToInt(ParamStr(3));
  If CompareString(LOCALE_USER_DEFAULT,NORM_IGNORECASE,PChar(ParamStr(4)),-1,'all',-1) = 2 Then
    begin
    even := 1;
    odd := 1;
  end
  Else If CompareString(LOCALE_USER_DEFAULT,NORM_IGNORECASE,PChar(ParamStr(4)),-1,'even',-1) = 2 Then
    begin
    even := 1;
  end
  Else If CompareString(LOCALE_USER_DEFAULT,NORM_IGNORECASE,PChar(ParamStr(4)),-1,'odd',-1) = 2 Then
    begin
    odd := 1;
  end
  Else Exit;
  fp := CreateFile(PChar(ParamStr(1)),GENERIC_READ Or GENERIC_WRITE,0,nil,OPEN_ALWAYS,0,0);
  If fp = INVALID_HANDLE_VALUE Then Exit;
  Try
    Repeat
      ReadFile(fp,buffer,BUFSIZE,BytesRead,nil);
      If Copy(Buffer,1,7) = '%%Page:' Then
        begin
        If doclevel = 0 Then
          begin
          Inc(page);
          prpage := DWORD((page >= beginpage) And (page <= endpage) And ((odd And (page Mod 2) <> 0) Or (even And (Not(page Mod 2)) <> 0)));
          If prpage <> 0 Then
            begin
            retval := 0;
            Exit;
          end;
        end;
      end
      Else If Copy(Buffer,1,15) = '%%BeginDocument' Then
        begin
        Inc(doclevel);
      end
      Else If Copy(Buffer,1,13) = '%%EndDocument' Then
        begin
        Dec(doclevel);
      end
      Else If Copy(Buffer,1,7) = '%%Trailer' Then
        begin
        If doclevel = 0 Then
          begin
          trailer := 1;
        end;
      end;
      If (page = 0) Or (prpage <> 0) Or (trailer <> 0) Then
        begin
        Writeln(buffer);
      end;
    Until (BytesRead = 0);
  Finally
    CloseHandle(fp);
  end;
  If retval <> 0 Then
    begin
    Writeln(Format('%s: No pages found',[programname]));
  end;
  Readln;
end.

Open in new window

0
 
LVL 1

Author Closing Comment

by:pucko
ID: 31568447
Thanks
0
 
LVL 1

Author Comment

by:pucko
ID: 24114280
Must be something that differs though in the way it works. Get different result and corrupted postscripts that are much bigger with the delphi code abowe
0
 
LVL 13

Expert Comment

by:ThievingSix
ID: 24117817
Well if you give me a file to use it with, what is supposed to be outputted I could help you with it further.
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

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

A lot of questions regard threads in Delphi.   One of the more specific questions is how to show progress of the thread.   Updating a progressbar from inside a thread is a mistake. A solution to this would be to send a synchronized message to the…
In this tutorial I will show you how to use the Windows Speech API in Delphi. I will only cover basic functions such as text to speech and controlling the speed of the speech. SAPI Installation First you need to install the SAPI type library, th…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

696 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