PostScript - 从文件到文件

时间:2014-02-13 00:18:21

标签: file line postscript

干杯,

我正在尝试使用PostScript从文件中读取char,然后将它们写入另一个文件。

我可以将所有字符推送到堆栈中:

(inputFile)(r)file 1 string readstring

但现在我无法将字符写入另一个文件。我试过了

(outputFile)(w)file = writestring

和其他方法,但似乎都没有。

编辑:代码

/infile (text.txt) (r) file def % open files and save file objects
/outfile (output.txt) (w) file def
/buff 1 string def % your buffer for reading operations
{ % loop
    infile buff readstring
    { %ifelse
         outfile (>) writestring
         outfile exch writestring
         outfile (<) writestring
         outfile (\n) writestring

    }
    { %else

            exit % exit the loop
    } ifelse
} bind loop

每个字符获取&gt;和&lt; ,但他们仍然在同一条线上

编辑:发现问题:输出文件不能有.txt entension

祝你好运

1 个答案:

答案 0 :(得分:1)

我认为你误解了PostScript的工作方式。它是一种基于堆栈的语言,因此运算符从堆栈中消耗它们的操作数,并将它们的结果(如果有的话)压入堆栈。所以要注释你的例子:

(inputFile)           % push a string with the filename onto the stack
(r)                   % push a string with the access mode onto the stack
file                  % the file operator consumes two string operands, opens
                      % a file and returns the file object on the stack
1 string              % create an empty string of maximum length 1
readstring            % readstring consumes a string object and a file object from
                      % the stack, it reads bytes from the file object until the string
                      % is full or reaches EOF. It then returns the substring filled,  
                      % and a boolean indicating the outcome.


(outputFile)          % push a string with the filename onto the stack
(w)                   % push a string with the access mode onto the stack
file                  % the file operator consumes two string operands, opens
                      % a file and returns the file object on the stack
=                     % consumes the top object on the stack, and writes a textual
                      % representation of the object to stdout (usually -file-)
writestring           % consumes two operands from the stack, a file object and a
                      % string to write. OOPS! no objects on the stack, so we generate
                      % a stackunderflow

现在,如果我假设您认为这两行代码是顺序的,那么我可以看到当我们到达writtring时我们将在堆栈上有一个字符串,但是有两个问题。首先,'='消耗了文件操作数,使其不存在。其次,如果删除'=',那么在调用write string之前堆栈上的内容是'(string)-file-',而操作数的顺序必须是'-file-(string)'。一个简单的'exch'将解决这个问题。

所以你的代码应该是:

(inputFile) (r) file 1 string readstring
(outputFile) (w) file exch writestring

我建议,在寻求帮助时,你要说出你所得到的错误,因为这可能有助于人们理解更复杂的问题。