TechiWarehouse.Com


Top 3 Products & Services

1.
2.
3.

Dated: Aug. 12, 2004

Related Categories

Pascal Programming

Introduction

PASCAL is a programming language named after the 17th century mathematican Blaise Pascal. Pascal : provides a teaching language that highlights concepts common to all computer languages, in other words once you learn PASCAL most other programming languages are very similar. standardises the language in such a way that it makes programs easy to write

History

Turbo Pascal is a popular version of Pascal, made by Borland/Inprise Inc. Pascal was originally designed for teaching and it still is. It is mostly used to teach students, but it has a built-in Assembler so its power can't be overlooked. Most people don't like it is that all its commands are words, so much typing! Anyway, it's a very good language to learn. It's structural, good for future careers in programming.

Pascal and C Language

Both C and Pascal are considered High Level Languages. They use English type statements that are converted to machine statements which are executed by computers.
C and Pascal programs are simple text files containing program statements. As such, they are created using a text editor. This is called the source program

Why Learn Pascal

Pascal TutorialDespite its fading away as the de facto standard, Pascal is still extremely useful. C and C++ are very symbolic languages. Where Pascal chooses words (e.g. begin-end), C/C++ chooses symbols ({-}). Also, C and C++ are not strongly-typed languages. In Pascal, mixing types often led to an error. In C/C++, nothing would happen. You could even treat pointers as integers and do pointer arithmetic with them. In this way, you could very easily crash your program. When the AP exam switched to C++, only a subset of C++ was adopted. Many features, like arrays, were considered too dangerous, and ETS provided its own "safe" version of these features. Java corrects many of these problems of C++ (there are no actual pointers in Java).

Another reason: speed and size. The Borland Pascal compiler is still lightning- fast. Borland has revitalized Pascal for Windows with Delphi, a Rapid-Application-Development environment. Instead of spending several hours writing a user interface for a Windows program in C/C++, you could do it in ten minutes with Delphi's graphical design tools. You could do the same in Visual BASIC, but Delphi is so much faster than Visual BASIC.

Thus, even after C, C++, and Java took over the programming world, Pascal retains a niche in the market. Many small-scale freeware, shareware, and open-source programs are written in Pascal/Delphi. So enjoy learning it while it lasts. It's a great introduction to computer programming. It's not scary like C, dangerous like C++, or abstract like Java. In another twenty years, you'll be one of the few computer programmers to know and appreciate Pascal.

Writing Programs

Pascal is very English like in its structures. This includes the use of "words", that isstrings of characters that identify elements within the program. There are many different kinds of words identifying variables, programs and subprograms (known as procedures and functions). The programmer gets to give meaning to many of these, but some are predefined

Reserve Words

There are a number of words which have a fixed meaning, and cannot be redefined by the programmer. The list follows. Generally these words identify program sections or program flow control structures

 

Standard identifiers

Standard idenfiers have a predefined meaning, but a programmer could override that definition with one of her or his own. While this is possible, it is not advisable, as this reduces "common understanding" of what a programmer was attempting at a given point in a program, making your program less maintainable.

Basic Program Components

Every Pascal program has the following three components.

Program heading: program identifier(input,output); Note that this is probably the only identifier which you only type once, so you can use more of the 64 characters available.
So, go ahead, create a really descriptive identifier.

Declaration section: var const Things that will be used later on in your program are declared here. Nothing really happens here, you're just telling Turbo Pascal what you need for later on.

Executable section: begin...end. Note that the end is followed by a period. All the statements inbetween the begin and end are things that you want your program to do: receive information, change it somehow, or output it to the screen or printer.

Writing Code in Pascal

Executable statement:

An executable statement consists of valid identifiers, standard identifiers, reserved words, numbers and/or characters together with appropriate punctuation. In a sense, an executable statement is much like a phrase within a sentence.

Semicolon as a separator. Every executable statement needs to be terminated with a semicolon. There is only one exception to this rule, and that is where the statement is followed by the word END.

Writing style - in my not so humble opinion there are two vital skills in writing style. This first is putting in line breaks! This might sound obvious, but Turbo Pascal does not require executable statements to be seperated by a line break, only by a semi-colon. But stringing lines together obscures them, so (especially since I mark you assignments!) don't do it!

The other skill is indenting. Basically everything between a begin and end should be indented one level. As we learn other programming structures, you will be indenting further levels. Indenting doesn't mean anything to Turbo Pascal, but it makes you programs a whole lot more human readable.

 

 

 

 

 

 

 

Pascal Compiler


A computer cannot understand the spoken or written language that we humans use in our day to day conversations, and likewise, we cannot understand the binary language that the computer uses to do it's tasks. It is therefore necessary for us to write instructions in some specially defined language, in this case Pascal, which we can understand, then have that very precise language converted into the very terse language that the computer can understand. This is the job of the compiler

A Pascal compiler is itself a computer program who's only job is to convert the Pascal program from our form to a form the computer can read and execute. The computer prefers a string of 1's and 0's that mean very little to us, but can be very quickly and accurately understood by the computer. The original Pascal program is called the "source code", and the resulting compiled code produced by the compiler is usually called an "object file".

One or more object files are combined with predefined libraries by a linker, sometimes called a binder, to produce the final complete file that can be executed by the computer. A library is a collection of pre-compiled "object code" that provides operations that are done repeatedly by many computer programs.
.

 

Let the Game Begin


First program in Pascal

In the short history of computer programming, one tradition has been created. The first program written in a new language is always a "Hello, world" program.

Copy and paste the following program into your IDE or text editor, then compile and run it:

                                   program Hello; begin (* Main *) writeln ('Hello, world.') end. (* Main *) 
     The output should look like                  Hello, world.  

Program Structure

The basic structure of a Pascal program is:

PROGRAM ProgramName (FileList);
CONST (* Constant declarations *)
TYPE (* Type declarations *)
VAR (* Variable declarations *) (* Subprogram definitions *)
BEGIN (* Executable statements *)
END.

The elements of a program must be in the correct order, though some may be omitted if not needed. Here's a program that does nothing, but has all the REQUIRED elements:
program DoNothing;
begin
end.

Pascal comments start with a (* and end with a *).
You can't nest comments: (* (* *) *) will yield an error because the compiler matches the first (* with the first *), ignoring everything inbetween. The second *) is left without its matching (*.
In Turbo Pascal, {Comment} is an alternative to (* Comment *). The opening brace signifies the beginning of a block of comments, and the ending brace signifies the end of a block of comments

Commenting has two purposes: first, it makes your code easier to understand. If you write your code without comments, you may come back to it a year later and have a lot of difficulty figuring out what you've done or why you did it that way. Another use of commenting is to figure out errors in your program. When you don't know what is causing an error in your code, you can comment out any suspect code segments. Remember the earlier restriction on nesting comments? It just so happens that braces {} supersede parenthesis-stars (* *). You will NOT get an error if you do this

{ (* Comment *) }

Identifier

Identifiers are names that allow you to reference stored values, such as variables and constants. Also, every program must be identified (hence the name) by an identifier.

Rules for identifiers:
Must begin with a letter from the English alphabet.
Can be followed by alphanumeric characters (alphabetic characters and numerals) and possibly the underscore (_). May not contain certain special characters.

Examples of special characters: ~ ! @ # $ % ^ & * ( ) _ + ` - = { } [ ] : " ; ' < > ? , . / | \
Pascal implementations may differ in their rules on special characters, especially the underscore.

Pascal is not case sensitive! MyProgram, MYPROGRAM, and mYpRoGrAm are equivalent. But for readability purposes, it is a good idea to use meaningful capitalization! Because C, C++, and Java, the dominant programming languages of today, are case- sensitive, future Pascal implementations may become case-sensitive.

 

Constant

Constants are referenced by identifiers, and can be assigned one value at the beginning of the program. The value stored in a constant cannot be changed.
Constants are defined in the constant section

const
Identifier1 = value;
Identifier2 = value;
Identifier3 = value;

Example:
const
Name = 'Tao Yue';
FirstLetter = 'a';
Year = 1997;
pi = 3.1415926535897932;
UsingNetscapeNavigator = TRUE;

The example has shown the main data types allowed in Pascal: strings, characters, integers, reals, and Booleans. Those data types will be further explained in the next section.

Note that in Pascal, characters are enclosed in single quotes, or apostrophes (')!

Constants are useful when you want to use a number in your programs that you know will change in the future. If you are writing a program for the British Parliament and want to display the name of the prime minister, you wouldn't want to hard-code the name every time you display it. It would be too time-consuming to find all the instances and change them later on. Instead, you would

const PrimeMinister = 'Winston Churchill';
and later change it to
const PrimeMinister = 'Tony Blair';

That way, the rest of your code can remain unchanged because they refer to the constant. Just the constant's value needs to be modified.

Variables and Data Types

Variables are similar to constants, but their values can be changed as the program runs. Unlike in BASIC and other loosely-typed languages, variables must be declared in Pascal before they can be used:
var
IdentifierList1 : DataType1;
IdentifierList2 : DataType2;
IdentifierList3 : DataType3


IdentifierList is a series of identifiers, separated by commas (,). All identifiers in the list are declared as being of the same data type.

The main data types in Pascal are: integer real char Boolean

More information on Pascal data types:
integer data type can contain integers from -32768 to 32767.
The real data type has a positive range from 3.4x10-38 to 3.4x1038.
Real values can be written in either fixed-point notation or in scientific notation, with the character E separating the mantissa from the exponent. Thus, 452.13 is the same as 4.5213e2
The char data type holds characters. Be sure to enclose them in single quotes, or apostrophes: 'a' 'B' '+' This data type can also hold system characters, such as the null character (ordinal value of 0) and the false-space character (ordinal value of 255).
The Boolean data type can have only two values: TRUE and FALSE

An example of declaring several variables is
var age, year, grade : integer;
circumference : real;
LetterGrade : char;
DidYouFail : Boolean;

Assignments and Operators

Once you have declared a variable, you can store values in it. This is called assignment.

To assign a value to a variable, follow this syntax:
    variable_name := expression;
Note that unlike other languages, whose assignment operator is simply an equals sign, Pascal uses a colon followed by an equals sign.

The expression can either be a single value:
    some_real := 385.385837;
or it can be an arithmetic sequence:
    some_real := 37573.5 * 37593 + 385.8 / 367.1;

The arithmetic operators in Pascal are:

Operator Operation Operands Result
+ Addition or unary positive real or integer real or integer
- Subtraction or unary negative real or integer real or integer
* Multiplication real or integer real or integer
/ Real division real or integer real
div Integer division integer integer
mod Modulus (remainder division) integer integer

 

div and mod only work on integers. / works on both reals and integers but will always yield a real answer. The other operations work on both reals and integers.

For operators that accept both reals and integers, the resulting data type will be integer only if all the operands are integer. It will be real if any of the operands are real.

Therefore,
    3857 + 68348 * 38 div 56834
will be integer, but
    38573 div 34739 mod 372 + 35730 - 38834 + 1.1
will be real because 1.1 is a real value.

Each variable can only be assigned a value that is of the same data type. Thus, you cannot assign a real value to an integer variable. However, certain data types are compatible with others. In these cases, you can assign a value of a lower data type to a variable of a higher data type. This is most often done when assigning integer values to real variables. Suppose you had this variable declaration section:

     var         some_int : integer;         some_real : real;

When the following block of statements executes,

     some_int := 375;      some_real := some_int;

some_real will have a value of 375.0, or 3.75e2.

In Pascal, the minus sign can be used to make a value negative. The plus sign can also be used to make a value positive. This, however, is unnecessary because values default to being positive.

Do not attempt to use two operators side by side!
    some_real := 37.5 * -2;
This may make perfect sense to you, since you're trying to multiply by negative-2. However, Pascal will be confused -- it won't know whether to multiply or subtract. You can avoid this by using parentheses:
    some_real := 37.5 * (-2);
to make it clearer.

The computer follows an order of operations similar to the one that you follow when you do arithmetic:
    * / div mod
    + -

The computer looks at each expression according to these rules:

  1. Evaluate all expressions in parentheses, starting from the innermost set of parentheses and proceeding to the outermost.
  2. Evaluate all multiplication and division from left to right.
  3. Evaluate all addition and subtraction from left to right.

 

The value of
    3.5 * (2 + 3)
will be 17.5.

Standard Functions

The arithmetic operators in Pascal are:

Operator Operation Operands Result
+ Addition or unary positive real or integer real or integer
- Subtraction or unary negative real or integer real or integer
* Multiplication real or integer real or integer
/ Real division real or integer real
div Integer division integer integer
mod Modulus (remainder division) integer integer

 

div and mod only work on integers. / works on both reals and integers but will always yield a real answer. The other operations work on both reals and integers.

For operators that accept both reals and integers, the resulting data type will be integer only if all the operands are integer. It will be real if any of the operands are real.

Therefore,
    3857 + 68348 * 38 div 56834
will be integer, but
    38573 div 34739 mod 372 + 35730 - 38834 + 1.1
will be real because 1.1 is a real value.

Each variable can only be assigned a value that is of the same data type. Thus, you cannot assign a real value to an integer variable. However, certain data types are compatible with others. In these cases, you can assign a value of a lower data type to a variable of a higher data type. This is most often done when assigning integer values to real variables. Suppose you had this variable declaration section:

     var         some_int : integer;         some_real : real;

When the following block of statements executes,

     some_int := 375;      some_real := some_int;

some_real will have a value of 375.0, or 3.75e2.

In Pascal, the minus sign can be used to make a value negative. The plus sign can also be used to make a value positive. This, however, is unnecessary because values default to being positive.

Do not attempt to use two operators side by side!
    some_real := 37.5 * -2;
This may make perfect sense to you, since you're trying to multiply by negative-2. However, Pascal will be confused -- it won't know whether to multiply or subtract. You can avoid this by using parentheses:
    some_real := 37.5 * (-2);
to make it clearer.

The computer follows an order of operations similar to the one that you follow when you do arithmetic:
    * / div mod
    + -

The computer looks at each expression according to these rules:

  1. Evaluate all expressions in parentheses, starting from the innermost set of parentheses and proceeding to the outermost.
  2. Evaluate all multiplication and division from left to right.
  3. Evaluate all addition and subtraction from left to right.

 

The value of
    3.5 * (2 + 3)
will be 17.5.

.

One Dimensional Arrays

Suppose you wanted to read in 5000 integers and do something with them. How would you store the integers?

You could use 5000 variables, lapsing into:
    aa, ab, ac, ad, ... aaa, aab, ... aba, ...
or you could use an array.

An array contains several storage spaces, all the same type. You refer to each storage space with the array name and with a subscript.

The type definition is:
    type
        typename = array [enumerated_type] of another_data_type;

The data type can be anything, even another array. Any enumerated type will do. You can specify the enumerated type inside the brackets, or use a predefined enumerated type. In other words,
  type
      enum_type = 1..50;
      arraytype = array [enum_type] of integer;

is equivalent to
  type
      arraytype = array [1..50] of integer;

This is how strings are actually managed. You declare:

   type       String = packed array [0..255] of char;

and use some kind of terminating character to signify the end of the string. Most of the time it's the null-character (ordinal number 0, or ord(0)). The packed specifier means that the array will be squeezed to take up the smallest amount of memory. This makes it possible to print out the entire array all at once rather than one-character at a time. In Turbo/Borland Pascal, there's a built-in string data type.

Arrays are useful if you want to store large quantities of data for later use in the program. They work especially well with for loops, because the index can be used as the subscript. To read in 50 numbers, assuming
    type arraytype = array[1..50] of integer;
and
    var myarray : arraytype;
you use

   for count := 1 to 50 do       read (myarray[count]);

 

Brackets [] enclose the subscript when referring to arrays.
    myarray[5] := 6;

.

Multidimensional Arrays

Suppose you wanted to read in 5000 integers and do something with them. How would you store the integers?

You could use 5000 variables, lapsing into:
    aa, ab, ac, ad, ... aaa, aab, ... aba, ...
or you could use an array.

An array contains several storage spaces, all the same type. You refer to each storage space with the array name and with a subscript.

The type definition is:
    type
        typename = array [enumerated_type] of another_data_type;

The data type can be anything, even another array. Any enumerated type will do. You can specify the enumerated type inside the brackets, or use a predefined enumerated type. In other words,
  type
      enum_type = 1..50;
      arraytype = array [enum_type] of integer;

is equivalent to
  type
      arraytype = array [1..50] of integer;

This is how strings are actually managed. You declare:

   type       String = packed array [0..255] of char;

and use some kind of terminating character to signify the end of the string. Most of the time it's the null-character (ordinal number 0, or ord(0)). The packed specifier means that the array will be squeezed to take up the smallest amount of memory. This makes it possible to print out the entire array all at once rather than one-character at a time. In Turbo/Borland Pascal, there's a built-in string data type.

Arrays are useful if you want to store large quantities of data for later use in the program. They work especially well with for loops, because the index can be used as the subscript. To read in 50 numbers, assuming
    type arraytype = array[1..50] of integer;
and
    var myarray : arraytype;
you use

   for count := 1 to 50 do       read (myarray[count]);

 

Brackets [] enclose the subscript when referring to arrays.
    myarray[5] := 6;

Loops

Looping means repeating a statement or compound statement over and over until some condition is met.

There are three types of loops:

  • fixed repetition - only repeats a fixed number of times
  • pretest - tests a Boolean expression, then goes into the loop if TRUE
  • posttest - executes the loop, then tests the Boolean expression

 

In Pascal, the fixed repetition loop is the for loop. The general form is:
    for index := StartingLow to EndingHigh do
        statement;

The index variable must be of an ordinal data type. You can use the index in calculations within the body of the loop, but you should not change the value of the index. An example of using the index is:

 
   sum := 0;
   for count := 1 to 100 do
      sum := sum + count;
The computer would do the sum the long way and still finish it in far less time than it took the mathematician Gauss to do the sum the short way (1+100 = 101. 2+99 = 101. See a pattern? There are 100 numbers, so the pattern repeats 50 times. 101*50 = 5050).

In the for-to-do loop, the starting value MUST be lower than the ending value, or the loop will never execute! If you want to count down, you should use the for-downto-do loop:
    for index := StartingHigh downto EndingLow do
        statement;

In Pascal, the for loop can only count in increments (steps) of 1.

.

While-DO Loop

The pretest loop has the following format:
    while BooleanExpression do
        statement;

The loop continues to execute until the Boolean expression becomes FALSE. In the body of the loop, you must somehow affect the Boolean expression by changing one of the variables used in it. Otherwise, an infinite loop will result:

     a := 5;      while a < 6 do         writeln (a);

 

Remedy this situation by changing the variable's value:

     a := 5;      while a < 6 do         begin            writeln (a);            a := a + 1         end;

 

The WHILE ... DO lop is called a pretest loop because the condition is tested before the body of the loop executes. So if the condition starts out as FALSE, the body of the while loop never executes

Repeat Until

The posttest loop has the following format:
    repeat
        statement1;
        statement2
    until BooleanExpression;

In a repeat loop, compound statements are built-in -- you don't need to use begin-end.

Also, the loop continues until the Boolean expression is TRUE, whereas the while loop continues until the Boolean expression is FALSE.

This loop is called a posttest loop because the condition is tested AFTER the body of the loop executes. The REPEAT loop is useful when you want the loop to execute at least once, no matter what the starting value of the Boolean expression is.

Records

A record allows you to keep related data items in one structure. If you want information about a person, you may want to know name, age, city, state, and zip.

To declare a record, you'd use:
    TYPE
        TypeName = record
          identifierlist1 : datatype1;
          ...
          identifierlistn : datatypen;
        end;

For example:

 
   type
      InfoType = record
Name : string;
Age : integer;
City, State : String;
Zip : integer;
                 end;

 

Each of the identifiers Name, Age, City, State, and Zip are referred to as fields. You access a field within a variable by:
    VariableIdentifier.FieldIdentifier
A period separates the variable and the field name.

There's a very useful statement for dealing with records. If you are going to be using one record variable for a long time and don't feel like type the variable name over and over, you can strip off the variable name and use only field identifiers. You do this by:
    WITH RecordVariable DO
        BEGIN
          ...
        END;

Example:

 
   WITH Info DO
      BEGIN
         Age := 18;
         ZIP := 90210;
      END;

Pointers in Pascal

A pointer is a data type which holds a memory address. To access the data stored at that memory address, you dereference the pointer.

To declare a pointer data type, you must specify what it will point to. That data type is preceded with a carat (^). For example, if you are creating a pointer to an integer, you would use this code:
          TYPE
            PointerType=^integer;

You can then, of course, declare variables to be of type PointerType

Before accessing a pointer, you must create a memory space for it. This is done with:
          New (PointerVariable);

To access the data at the pointer's memory location, you add a carat after the variable name. For example, if PointerVariable was declared as type PointerType (from above), you can assign the memory location a value by using:
          PointerVariable^ := 5;

After you are done with the pointer, you must deallocate the memory space. Otherwise, each time the program is run, it will allocate more and more memory until your computer has no more. To deallocate the memory, you use the Dispose command:
          Dispose(PointerVariable);

A pointer can be assigned to another pointer. However, note that since only the address, not the value, is being copied, once you modify the data located at one pointer, the other pointer, when dereferenced, also yields modified data. Also, if you free (or deallocate) a pointer, the other pointer now points to meaningless data.

What is a pointer good for? Why can't you just use an integer in the examples above instead of a pointer to an integer? The answer is that, in this situation, a pointer was clearly not needed. The use of pointers is in creating dynamically-sized data structures. If you need to store many items of one data type in order, you can use an array. However, your array has a predefined size. If you don't have a large enough size, you may not be able to accommodate all the data. If you have a huge array, you take up a lot of memory when sometimes that memory is not being used. A dynamic data structure, on the other hand, takes up only as much memory as is being used. What you do is to create a data type that points to a record. Then, the record has that pointer type as one of its fields. For example, stacks and queues can all be implemented using this data structure:
          Type
          PointerType = ^RecordType;
          RecordType = record;
          data : integer;
          next : PointerType;
          end;

Each element points to the next. To know when a chain of records has ended, the next field is assigned a value of Nil.

 

Input

Input means to read data into memory, either from the keyboard, the mouse, or a file on disk.

We will not get into mouse input in detail, because that syntax differs from machine to machine, and may require a complicated interrupt call to the mouse driver. If you would like to see the source code for a mouse support unit for DOS, click here. This unit will not work under Windows, Macintosh, or X-Windows, because these operating systems handle all mouse input for you and do not let you interface with the mouse directly.

The basic format for reading in data is:
    read (Variable_List);
Variable_List is a series of variable identifiers separated by commas.

read, however, does not go to the next line. This can be a problem with character input, because the end-of-line character is read as a space.

To read data and then go on to the next line, use
    readln (Variable_List);

Suppose you had this input from the user, and a, b, c, and d were all integers.
    45 97 3
    1 2 3

This would be the result of various statements:

Statement(s) a b c d
read (a);
read (b);
45 97
readln (a);
read (b);
45 1
read (a, b, c, d); 45 97 3 1
readln (a, b);
readln (c, d);
45 97 1 2

 

You see, the read statement does not skip to the next line unless necessary, whereas the readln statement is just a read statement that skips to the next line at the end of reading.

When reading in integers, all spaces are skipped until a numeral is found. Then all subsequent numberals are read, until a non-numeric character is reached (including, but not limited to, a space).
    8352.38
When an integer is read, its value becomes 8352.
If, immediately afterwards, you read in a character, the value would be '.'

Suppose you tried to read in two integers. That would not work, because when the computer looks for data to fill the second variable, it sees the '.' and stops, saying, "I couldn't find any data to read."

With real values, the computer also skips spaces and then reads as much as can be read. However, there is one restriction: a real that has no whole part must begin with 0.
    .678
is invalid, and the computer can't read in a real, but
    0.678
is fine.

Make sure that all identifiers in the argument list refer to variables! Constants cannot be assigned a value, and neither can literal values.

Output

For writing data to the screen, there are also two statements:
    write (Argument_List);
    writeln (Argument_List);

The writeln statement skips to the next line when done.

You can use strings in the argument list, either constants or literal values. If you want to display an apostrophe within a string, use two consecutive apostrophes.

Using Files in Pascal

Using files for input/output is a bit of a sticking point. Different Pascal compilers do it in different ways. However, the method of reading/writing to the file is the same across all compilers:
    read (file_variable, argument_list);
    write (file_variable, argument_list);

Same thing with readln and writeln.

In addition, most Pascal systems require that you declare a file variable in the variable section:
    var
        ...
        filein, fileout : text;

The text data type is usually used. There are other file types, but that's left for a later lesson.

The differences between Pascal compilers arises when you open a file for reading or writing. In most Pascal compilers, including Metrowerks Codewarrior and the Pascal translator included with Unix/Linux, use:
    reset (file_variable, 'filename.extension');
to open a file for reading. Use:
    rewrite (file_variable, 'filename.extension');
to open a file for writing. Note that you can't open a file for both reading and writing. A file opened with reset can only be used with read and readln. A file opened with rewrite can only be used with write and writeln.

Turbo Pascal does it differently. First you assign a filename to a variable, then you call reset or rewrite using only the variable.

     assign (file_variable, 'filename.extension');      reset (file_variable)

The method of representing the path differs depending on your operating system. Examples:

   Unix:    ~login_name/filename.ext    DOS/Win: c:\directory\name.pas    Mac:     Disk_Name:Programs Directory:File Name.pas

 

You should close your file before your program ends! This is the same for all compilers:
    close (File_Identifier);

Here's an example of a program that uses files. This program was written for Turbo Pascal and DOS, and will create file2.txt with the first character from file1.txt:

                  program CopyOneByteFile;    var       mychar : char;       filein, fileout : text;    begin       assign (filein, 'c:\file1.txt');       reset (filein);       assign (fileout, 'c:\file2.txt');       rewrite (fileout);       read (filein, mychar);       write (fileout, mychar);       close(filein);       close(fileout)    end 

Now that you've gotten free know-how on this topic, try to grow your skills even faster with online video training. Then finally, put these skills to the test and make a name for yourself by offering these skills to others by becoming a freelancer. There are literally 2000+ new projects that are posted every single freakin' day, no lie!


Previous Article

Next Article


Josephay J's Comment
thanks , but am still need the help since am not good under this part
12 Wed Dec 2012
Admin's Reply:

You're welcome ask a particular question that maybe one of the other visitors may know something about. And if they like, they can help you out with your query.




raymart's Comment
can u give me some problem and its program?
27 Thu Sep 2012
Admin's Reply:



Mabr's Comment
hi.. i'm a pascal beginner.. can you please email me a simple tutorial notes to understand about it.. i'm still in stuck..
19 Tue Jun 2012
Admin's Reply:

Sorry Mabr...we're not supposed to be email info.




Aminu Umar's Comment
Very good work, think I will adopt it in my Introduction to Pascal Programming class.
11 Fri May 2012
Admin's Reply:

Go for it Aminu.




Ahmed Mohammed Azare's Comment
This is the first well explained programming book I 've ever seen. I need more from you.
12 Thu Jan 2012
Admin's Reply:

 Thank you Ahmed :) we will try our best.




jugbit's Comment
pls, i need a good turbo pascal software. and a short note on the following 1. semantic error 2. translation error 3. execution error most grateful in advance.
23 Fri Dec 2011
Admin's Reply:

Hi Jugbit, we'll be looking into posting some Pascal stuff by end of January.




kim's Comment
didnt mention anything abt case statements :(
24 Thu Nov 2011
Admin's Reply:

That will probably require an in-depth tutorial in itself.




ESIMINDA HENRY 's Comment
HI it is a nice tutorials but I have a problem invoking a printer with turbo pascal. I will be happy if you should provide help thanks
25 Thu Aug 2011
Admin's Reply:

 Hi Esiminda

Well to do something like that you need to study IO Devices commands in pascal. i ll see what i can do with that. thank you.




Jimbo's Comment
Re append with blockwrite, seek to the end of the file first.
12 Tue Apr 2011
Admin's Reply:




Temidjoy's Comment
Nice
05 Tue Apr 2011
Admin's Reply:

Thanks




Babatunde's Comment
I just started learning pascal
17 Thu Feb 2011
Admin's Reply:

Good for you. Even as a beginner, consider yourself in the top 2 percentile of the world population. Most people don't have a clue in Pascal, even as a beginner. Kudos to you for starting.




Jonah leonard ndaks's Comment
ITS A NICE ONE,HOPE TO SEE MORE.
29 Mon Nov 2010
Admin's Reply:

Thanks




Oskar's Comment
It seems like a very nice tutorial, can you please send it to my email?
25 Mon Oct 2010
Admin's Reply:

Can't do emails, sorry.




Andre''s Comment
I would like to know how i can put an array in a repeat until loop
15 Fri Oct 2010
Admin's Reply:

I'm not sure...can anyone reading this help?




olabode olaniran's Comment
Excellent tutoria well done
27 Fri Aug 2010
Admin's Reply:

Thanks.




martin's Comment
hi i have liked it. pliz send the tutorial to my e mail.
05 Mon Jul 2010
Admin's Reply:

Emailed Away




jonnex's Comment
wonderful &important teachings.
24 Thu Jun 2010
Admin's Reply:

Thanks Jonnex .




hellen's Comment
so wonderful please send me in my email
12 Fri Mar 2010
Admin's Reply:

i would like to help but what exactly you are looking for




Jo Harvey's Comment
What about turbo pascal FILE typ and blockread and blockwrite? very fast and efficient, but how do you append to a file with blockwrite?
04 Thu Feb 2010
Admin's Reply:

I urge readers to help out with this one




Inawwarminister's Comment
Yep, I am really thankful for this article. Real good job for the writers!
24 Sun Jan 2010
Admin's Reply:

I'm glad to hear you like it




vasanta's Comment
this tutorial is good and program explination better then other books.
07 Sat Nov 2009





Facebook