Free as Freedom, not Free as Free Pizza!” />

-

Udruženje Informatičara BiH - Cross-platform and Portable Development With PHP, LAMP/WAMP development, AJAX and Javascript, ASP, dot NET, C sharp, C++, C, VB, Oracle, tutorials and tips...
Free as Freedom, not Free as Free Pizza!


 
Web http://www.uibih.co.nr

Add to Google

Friday, October 27, 2006

How to upload File with PHP?

The HTML Form

This script will allow you to upload files from your browser to your hosting, using PHP. The first thing we need to do is create an HTML form that allows people to choose the file they want to upload.
<form enctype="multipart/form-data" action="upload.php" method="POST">

Please choose a file: <input name="uploaded" type="file" /><br />

<input type="submit" value="Upload" />

</form>

This form sends data to the file "upload.php", which is what we will be creating next to actually upload the file.

Uploading the File

The actual file upload is very simple:
This very small piece of code will upload files sent to it by your HTML form.

The first line $target = "upload/"; is where we assign the folder that files will be uploaded to. As you can see in the second line, this folder is relative to the upload.php file.
So for example, if your file was at
  1. www.yours.com/files/upload.php then it would upload files to www.yours.com/files/upload/yourfile.gif. Be sure you remember to create this folder!
  2. We are not using $ok=1; at the moment but we will later in the tutorial.
  3. We then move the uploaded file to where it belongs using move_uploaded_file (). This places it in the directory we specified at the beginning of our script. If this fails the user is given an error message, otherwise they are told that the file has been uploaded.

Limit the File Size

if ($uploaded_size > 350000)
{
echo "Your file is too large.
";
$ok=0;
}
Assuming that you didn't change the form field in our HTML form (so it is still named uploaded), this will check to see the size of the file. If the file is larger than 350k, they are given a file too large error, and we set $ok to equal 0.

You can change this line to be a larger or smaller size if you wish by changing 350000 to a different number. Or if you don't care about file size, just leave these lines out.

Limit Files by Type

if ($uploaded_type =="text/php")
{
echo "No PHP files
";
$ok=0;
}
The code above checks to be sure the user is not uploading a PHP file to your site. If they do upload a PHP file, they are given an error, and $ok is set to 0.
if (!($uploaded_type=="image/gif")) {
echo "You may only upload GIF files.
";
$ok=0;
}
In our second example we only allow users to upload .gif files, and all other types are given an error before setting $ok to 0. You can use these basic examples to allow or deny any specific file types.

Putting It Together

350000)
{
echo "Your file is too large.
";
$ok=0;
}

//This is our limit file type condition
if ($uploaded_type =="text/php")
{
echo "No PHP files
";
$ok=0;
}

//Here we check that $ok was not set to 0 by an error
if ($ok==0)
{
Echo "Sorry your file was not uploaded";
}

//If everything is ok we try to upload it
else
{
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ".
basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
}
?>

Final Thoughts

Obviously if you are allowing file uploads you are leaving yourself open to people uploading lots of undesirable things. One precaution is not allowing them to upload any php, html, cgi, etc. files that could contain malicious code. This provides more safety but is not sure fire protection.

Another idea is to make the upload folder private, so that only you can see it. Then once you have seen what has been uploaded, you can approve (move) it or remove it. Depending on how many files you plan on receiving this could be time consuming and impractical.

In short, this script is probably best kept in a private folder. We don't recommend putting it somewhere where the public can use it, or you may end up with a server full of useless or potentially dangerous files. If you really want the general public to be able to utilize your server space, we suggest writing in as much security as possible.

And as u see its not big deal either to write such code ;))

Common Mistakes in C

Mistakes are a fact of life. When you write a computer program in C, the compiler must convert your source code to machine code, so there must be some very strict rules governing how you use the language. Leave out a comma where one is expected, or add a semicolon where you shouldn\u2019t, and the compiler won\u2019t be able to translate your program into machine code.

You\u2019ll be surprised just how easy it is to introduce typographical errors into a program, even after years of practice. If you\u2019re lucky, these errors will be picked up when you compile or link your program. If you\u2019re really unlucky, they can result in your program apparently working fine but producing some intermittent erratic behavior. You can end up spending a lot of time tracking these errors down.

Of course, it\u2019s not only typographical errors that cause problems. You\u2019ll often find that your detailed implementation is just not right. Where you\u2019re dealing with complicated decisions in your program, it\u2019s easy to get the logic wrong. Your program may be quite accurate from a language point of view, and it may compile and run without a problem, but it won\u2019t produce the right answers. These kinds of errors can be the most difficult to find.

Points to Remember

It would be a good idea to review what you\u2019ve gleaned from your first program. You can do this by looking at the overview of the important points in Figure 1-4.

Summary

You\u2019ve reached the end of the first chapter, and you\u2019ve already
written a few programs in C. You\u2019ve covered quite a lot of ground, but
at a fairly gentle pace. The aim of this chapter was to introduce a few basic
ideas rather than teach you a lot about the C programming language. You should
be confident about editing, compiling, and running your programs. You probably
have only a vague idea about how to construct a C program at this point. It
will become much clearer when you\u2019ve learned a bit more about C and written
some programs with more meat to them.


In the next chapter, you\u2019ll move on to more complicated things than just producing text output using theprintf()function. You\u2019ll manipulate information and get some rather more interesting results. And by the way, theprintf()function does a whole lot more than just display text strings\u2014as you\u2019ll see soon.

Exercises

The following exercises enable you to try out what you\u2019ve learned in this chapter. If you get stuck, look back over the chapter for help. If you\u2019re still stuck, you can download the solutions from the Downloads area of the Apress website (http://www.apress.com), but that really should be a last resort.




Figure 1-4. Elements of
a simple program


Exercise 1-1. Write a program that will output your name and address using a separate printf()statement for each line of output.

Exercise 1-2. Modify your solution for the previous exercise so that it produces all the output using only one printf() statement.

Exercise 1-3. Write a program to output the following text, exactly as it appears here:

--------------------------------------------------
"It's freezing in here," he said coldly.
--------------------------------------------------

Functions and Modular Programming in C

The word “function” has appeared a few times so far in this chapter with reference to main(), printf(), function body, and so on. Let’s explore in a little more depth what functions are and why they’re important.

Most programming languages, including C, provide a way of breaking up a program into segments, each of which can be written more or less independently of the others. In C these segments are called functions. The program code in the body of one function is completely insulated from that of other functions. A function will have a specific interface to the outside world in terms of how information is transferred to it and how results generated by the function are transmitted back from it. This interface is specified in the first line of the function, where the function name appears.

Figure 1-3 shows a simple example of a program to analyze baseball scores that is composed of four modules.


Figure 1-3.  Modular programming

Each of the four modules does a specific, well-defined job. Overall control of the sequence of operations in the program is managed by one module,main(). There is a module to read and check the input data and another module to do the analysis. Once the data has been read in and analyzed, a fourth module has the task of outputting the team and player rankings.

Segmenting a program into manageable chunks is a very important aspect to programming, so let’s go over the reasons for doing this:

  • Dividing the program into a number of separate functions allows each function to be written and tested separately. This greatly simplifies the process of getting the total program to work.
  • Several separate functions are easier to handle and understand than one huge function.
  • Libraries are just sets of functions that people tend to use all the time. Because they’ve been prewritten and pretested, you know they’ll work, so you can use them without worrying about their code details. This will accelerate your program development, by allowing you to concentrate on your own code, and it’s a fundamental part of the philosophy of C. The richness of the libraries greatly amplifies the power of the language.
  • You can accumulate your own libraries of functions that are applicable to the sorts of programs that you’re interested in. If you find yourself writing a particular function frequently, you can write a generalized version of it to suit your needs and build this into your own library. Then, whenever you need to use that particular function, you can simply use your library version.
  • In the development of very large programs, which can vary from a few thousand to millions of lines of code, development can be undertaken by teams of programmers, with each team working with a defined subgroup of the functions that make up the whole program.

You’ll learn about C functions in greater detail in Chapter 8. Because the structure of a C program is inherently functional, you’ve already encountered one of the standard library functions in one of this chapter’s earliest examples: the functionprintf().

.........................................................................................

Try It Out: Exercising What You Know

Let’s now look at an example that puts into practice what you’ve learned so far. First, have a look at the following code and see whether you can understand what it does without running it. Then type it in; compile, link, and run it; and see what happens.

/* Program 1.7 A longer program */
#include <stdio.h>    /* Include the header file for input and output */
void main()
{
  printf("Hi there!\n\n\nThis program is a bit");
  printf(" longer than the others.");
  printf("\nBut really it's only more text.\n\n\n\a\a");
  printf("Hey, wait a minute!! What was that???\n\n");
  printf("\t1.\tA bird?\n");
  printf("\t2.\tA plane?\n");
  printf("\t3.\tA control character?\n"); 
  printf("\n\t\t\b\bAnd how will this look when it prints out?\n\n");
}

The output will be as follows:

----------------------------------------------------------------------Hi there!
This program is a bit longer than the others.
But really it's only more text.
Hey, wait a minute!! What was that???
  1.  A
bird?
  2. 
A plane?
  3. 
A control character?
    And how will this look when it prints out?

--------------------------------------------

HOW IT WORKS

The program looks a little bit complicated, largely because the text strings between parentheses include a lot of escape sequences. Each text string is bounded by a pair of double quotation marks. However, the program is just a succession of calls to theprintf()function, and it demonstrates that output to the screen is controlled by what you pass to theprintf()function. Let’s look at this program in detail.

You include thestdio.hfile through the preprocessing directive:

#include <stdio.h>    /* Include the header file for input and output */

You can see that this is a preprocessing directive because it begins with#. Thestdio.hfile provides the definitions you need to be able to use theprintf()function.

You then define the start of the functionmain()and specify that it doesn’t return a value with this line:

void main()

The opening brace on the next line indicates that the body of the function follows:

{

The next statement calls the standard library functionprintf()to outputHi there!to your display screen, followed by two blank lines and the phraseThis program is a bit.

printf("Hi there!\n\n\nThis program is a bit");

The two blank lines are produced by the three\nescape sequences. Each of these starts a new line when the characters are written to the display. The first ends the line containingHi there!, and the next two produce the two empty lines. The textThis program is a bitappears on the fourth line of output. You can see that this one line of code produces a total of four lines of output on the screen.

The next line of output produced by the nextprintf()starts at the character position immediately following the last character in the previous output. The next statement outputs the textlonger than the others.with a space as the first character of the text:

printf(" longer than the others.");

This output will simply continue where the last line left off, following thetinbit. This means that you really do need the space at the beginning of the text, otherwise the computer will displayThis program is a bitlonger than the others, which isn’t what you want.

The next statement starts its output on a new line, immediately following the previous line, because of the\nat the beginning of the text string between double quotation marks:

printf("\nBut really it's only more text.\n\n\n\a\a");

It then displays the text and adds two empty lines (because of the three\nescape sequences) and beeps twice. The next output to the screen will start at the beginning of the line that follows the second empty line produced here.

The next output is produced by the following statement:

printf("Hey, wait a minute!! What was that???\n\n");

This outputs the text and then leaves one empty line. The next output will be on the line following the empty line.

Each of the next three statements inserts a tab, displays a number, inserts another tab followed by some text, and ends with a new line. This is useful for making your output easier to read:

printf("\t1.\tA bird?\n");
printf("\t2.\tA plane?\n");
printf("\t3.\tA control character?\n");

This produces three numbered lines of output.

The last statement that produces output adds a new line, so that there will be an empty line after the previous output. Two tabs are then sent to the display, followed by two backspaces, which moves your cursor back two spaces from the last tab position. Lastly, the text is displayed, and two newline characters are sent to the display:

printf("\n\t\t\b\bAnd how will this look when it prints out?\n\n");

The closing brace marks the end of the function body:

}

.............................................

Developing Programs in C

The process of developing programs in C may not be evident if you’ve never written a program before. However, it’s very similar to many other situations in life in which, at the beginning, it just isn’t clear how you’re going to achieve your objective. Normally, you start with an idea of what you want to achieve, but you need to translate this into a more precise specification of what you want. Once you’ve reached this more precise specification, you can work out the series of steps that will lead to your final objective. So having an idea that you want to build a house just isn’t enough. You need to know what kind of house you want, how large it’s going to be, what kinds of materials you have to build it with, and where you want to build it. This kind of detailed planning is also necessary when you want to write a program.

Let’s go through the basic steps that you need to follow when you’re writing a program. The house analogy is a useful one, so we’ll work with it for a while.

Understanding the Problem

The first step is to get a clear idea of what you want to do. It would be lunacy to start building your house before you had established what facilities it should provide: how many bedrooms, how many bathrooms, how big it’s going to be, and so on. All these things affect the cost of the house in terms of materials and the work involved in building it. Generally, it comes down to a compromise that best meets your needs within the constraints of the money, the workforce, and the time that’s available for you to complete the project.

It’s the same with developing a program of any size. Even for a relatively straightforward problem, you need to know what kind of input to expect, how the input is to be processed, and what kind of output is required—and how it’s going to look. The input could be entered with the keyboard, but it might also involve data from a disk file or information obtained over a telephone line or a network. The output could simply be displayed on the screen, or it could be printed; perhaps it might involve updating a data file on disk. For more complex programs, you’ll need to look at many more aspects of what the program is going to do. A clear definition of the problem that your program is going to solve is an absolutely essential part of understanding the resources and effort needed for the creation of a finished product. Considering these details also forces you to establish whether or not the project is actually feasible.

Detailed Design

To get the house built, you’ll need detailed plans. These plans enable the construction workers to do their job and the plans describe in detail how the house will go together—all the dimensions, the materials to use, and so on. You’ll also need a plan of what is to be done and when. For example, you’ll want the foundation dug before the walls are built, so the plan must involve segmenting the work into manageable units to be performed in a logical sequence.

It’s the same with a program. You’ll need to specify what the program does by dividing it into a set of well-defined and manageable chunks that are reasonably self-contained. You’ll also need to detail the way in which these chunks connect, as well as what information each chunk will need when it executes. This will enable you to develop the logic of each chunk, relatively independently from the rest of the program. If you treat a large program as one huge process that you try to code as a single chunk, chances are that you’ll never get it to work.

Implementation

Given the detailed design of a house, the work can start. Each group of construction workers will need to complete its part of the project at the right time. Each stage will need to be inspected to check that it’s been done properly before the next stage begins. Omitting these checks could easily result in the whole house collapsing.

Of course, if a program is large, you’ll write the source code one unit at a time. As one part is completed, you can write the code for the next. Each part will be based on the detailed design specifications, and you’ll verify that each piece works, as far as you can, before proceeding to the next. In this way, you’ll gradually progress to a fully working program that does everything you originally intended.

Testing

The house is complete, but there are a lot of things that need to be tested: the drainage, the water and electricity supplies, the heating, and so on. Any one of these areas can have problems that the contractors need to go back and fix. This is sometimes an iterative process, in which problems with one aspect of the house can be the cause of things going wrong somewhere else.

The mechanism with a program is similar. Each of your program modules—the pieces that make up your program—will need to be tested individually. When they don’t work properly, you need to debug them. Debugging is the process of finding and correcting errors in your program. This term is said to have originated in the days when finding the errors in a program involved tracing where the information went and how it was processed by using the circuit diagram for the computer. The story goes that it was discovered how a computer program error was caused by an insect shorting part of the circuit in the computer. The problem was caused by a bug. Subsequently, the term bug was used to refer to any error in a program.

With a simple program, you can often find an error simply by inspecting the code. In general, though, the process of debugging usually involves adding extra program code to produce output that will enable you to check what the sequence of events is and what intermediate values are produced in a program. With a large program, you’ll also need to test the program modules in combination because, although the individual modules may work, there’s no guarantee that they’ll work together! The jargon for this phase of program development is integration testing.

The Body of a Function in C

The general structure of the functionmain()is illustrated in Figure 1-2.


Figure 1-2.  Structure of the function main()

The function body is the bit between the opening and closing braces that follow the line where the function name appears. The function body contains all the statements that define what the function does. The example’s functionmain()has a very simple function body consisting of just one statement:

 

{

/* This marks the beginning of main() */

 

printf("Beware the Ides of March!");

/* This line displays a quotation

*/

}

 

/* This marks the end of main()

*/

Every function must have a body, although the body can be empty and just consist of the two braces without any statements between them. In this case, the function will do nothing.

You may wonder where the use is for a function that does nothing. Actually, this can be very useful when you’re developing a program that will have many functions. You can declare the set of (empty) functions that you think you’ll need to write to solve the problem at hand, which should give you an idea of the programming that needs to be done, and then gradually create the program code for each function. This technique helps you to build your program in a logical and gradual manner.


NOTE 
You can see that I’ve aligned the braces one below the other. I’ve done this to make it clear where the block of statements that the braces enclose starts and finishes. Statements between braces are usually indented by a fixed amount—usually two or more spaces so that the braces stand out. This is good programming style, as the statements within a block can be readily identified.

Outputting Information

The body of the example’s functionmain()includes only one statement, which calls theprintf()function:

printf("Beware the Ides of March!"); /* This line displays a quotation */

As I said,printf()is a standard library function, and it outputs information to the display screen based on what appears between the parentheses that immediately follow the function name. In this case, the call to the function displays a simple piece of Shakespearean advice that appears between the double quotes. Notice that this line does end with a semicolon.

Arguments

Items enclosed between the parentheses following a function name, as with theprintf()function, are called arguments. When there is more than one argument to a function, they must be separated by commas.

If you don’t like the quotation in this example’s argument, you could display something else by simply including your own choice of words, within double quotes, between the parentheses. For instance, you might prefer a line from Macbeth:

printf("Out, damned Spot! Out I say!");

Try using this in the example. When you’ve modified the source code, you need to compile and link the program again before executing it.


NOTE 
As with all executable statements in C (as opposed to defining or directive statements) theprintf()line must have a semicolon at the end. As you’ve seen, a very common error, particularly when you first start programming in C, is to forget the semicolon.

Control Characters

You could alter the program to display two sentences on separate lines. Try typing in the following code:

/* Program 1.4 Another Simple C Program - Displaying a Quotation */
#include <stdio.h>
void main()
{
 
printf("\nMy formula for success?\nRise early, work late, strike oil.");
}

The output from this program looks like this:

----------------------------------------------------------------------
My formula for success?
Rise early, work late, strike oil.
--------------------------------------------

Look at theprintf()statement. At the beginning of the text and after the first sentence, you insert the characters\n. The combination\nactually represents one character: a newline character.

The backslash (\) is of special significance in a text string. It indicates the start of an escape sequence. Escape sequences are used to insert characters in a string that would otherwise be impossible to specify, such as tab and newline, or would confuse the compiler, such as a double quote that you use to delimit a string. The character following the backslash indicates what character the escape sequence represents. In this case, it’snfor newline, but there are plenty of other possibilities. Obviously, if a backslash is of special significance, you need a way to specify a backslash in a text string. To do this, you simply use two backslashes:\\. Similarly, if you actually want to display a double quote character, you can use\".

Type in the following program:

/* Program 1.5 Another Simple C Program - Displaying Great Quotations */
#include <stdio.h>
void main()
{
  printf("\n\"It is a wise father that knows his own child.\"
         Shakespeare");
}

The output displays the following text:

----------------------------------------------------------------------
"It is a wise father that knows his own child." Shakespeare
----------------------------------------------------------------------

You can use the\aescape sequence in an output string to sound a beep to signal something interesting or important. Enter and run the following program:

/* Program 1.6 A Simple C Program–Important */
#include <stdio.h>
void main()
{
  printf("\nBe careful!!\a");
}

The output of this program is sound and vision. Listen closely and you should hear a beep through the speaker in your computer.

----------------------------------------------------------------------
Be careful!!
--------------------------------------------

The\asequence represents the “bell” character. Table 1-1 shows a summary of the escape sequences that you can use.

Table 1-1. Escape Sequences

Escape Sequence

Description

\n

Represents a newline character

\r

Represents a carriage return

\b

Represents a backspace

\f

Represents a form-feed character

\t

Represents a horizontal tab

\v

Represents a vertical tab

\a

Inserts a bell (alert) character

\"

Inserts a double quote (")

\'

Inserts a single quote (')

\\

Inserts a backslash (\)

Try displaying different lines of text on the screen and alter the spacing within that text. You can put words on different lines using\n, and you can use\tto space the text. You’ll get lot more practice with these as you progress through the book.

Dissecting a Simple Program

Now that you’ve written and compiled your first program, let’s go through another that’s very similar and see what the individual lines of code do. Have a look at this program:

/* Program 1.3 Another Simple C Program - Displaying a Quotation */
#include <stdio.h>
void main()
{
 
printf("Beware the Ides of March!");
}

This is virtually identical to your first program. Even so, you could do with the practice, so use your editor to enter this example and see what happens when you compile and run it. If you type it in accurately, compile it, and run it, you should get the following output:

----------------------------------------------------------------------
Beware the Ides of March!
--------------------------------------------

Comments

Look at the first line of code in the preceding example:

/* Program 1.3 Another Simple C Program - Displaying a Quotation */

This isn’t actually part of the program code, in that it isn’t telling the computer to do anything. It’s simply a comment, and it’s there to remind you, or someone else reading your code, what the program does. Anything between/*and*/is treated as a comment. As soon as your compiler finds/*in your source file, it will simply ignore anything that follows until it finds the matching*/that marks the end of the comment. This may be on the same line, or it can be several lines further on. Whatever is between/*and*/will be completely ignored by the compiler, even if it looks like program code.

You should try to get into the habit of documenting your programs, using comments as you go along. Your programs will, of course, work without comments, but when you write longer programs you may not remember what they do or how they work. Put in enough comments to ensure that, a month from now, you (and any other programmer) can understand the aim of the program and how it works.

As I said, comments don’t have to be in a line of their own. A comment is everything between/*and*/, wherever/*and*/are in your code. Let’s add some more comments to the program:

/* Program 1.3 Another Simple C Program - Displaying a Quotation */

#include <stdio.h>

/* This is a preprocessor directive

*/

void main()

/* This identifies the function main() */

{

/* This marks the beginning of main()

*/

 

printf("Beware the Ides of March!"); /* This line displays a quotation

*/

}

/* This marks the end of main()

*/

 

You can see that using comments can be a very useful way of explaining what’s going on in the program. You can place comments wherever you want in your program, and you can use them to explain the general objectives of the code as well as the specifics of how the code works. You can also use comments to identify the author of the code and to assert your copyright if you wish.

Preprocessing Directives

Look at the following line of code:

#include <stdio.h>           /* This is a preprocessing directive */

This isn’t strictly part of the executable program, but it is essential in this case—in fact, the program won’t work without it. The symbol#indicates this is a preprocessing directive, which is an instruction to your compiler to do something before compiling the source code. The compiler handles these directives during an initial preprocessing phase before the compilation process starts. There are quite a few preprocessing directives, and they’re usually placed at the beginning of the program source file.

In this case, the compiler is instructed to “include” in your program the contents of the filestdio.h. This file is called a header file, because it’s usually included at the head of a program. It defines information about some of the functions that are provided by the standard C library. The header file will contain C source code and other preprocessor directives. In this case, as you’re using theprintf()function from the standard library, you have to include thestdio.hheader file. This is becausestdio.hcontains the information that the compiler needs to understand whatprintf()means, as well as other functions that deal with input and output. All header files in C have file names with the extension.h. You’ll use other C header files later in the book.


NOTE 
It’s common practice to write the header file names in the#includedirective in lowercase letters.

Every C compiler that conforms to the American National Standards Institute (ANSI) standard for the language will have a set of standard header files supplied with it. Header files primarily contain definitions relating to standard library functions that are available with C. Although all ANSI standard C compilers will support the same set of standard library functions and will have the same set of standard header files available, there may be extra library functions provided with a particular compiler that may not be available with other compilers.

Defining the main() Function

The next four statements define the functionmain():

void main()

/* This identifies the function main() */

{

/* This marks the beginning of main()

*/

 

printf("Beware the Ides of March!"); /* This line displays a quotation

*/

}

/* This marks the end of main()

*/

A function is just a named block of code between braces that carries out some specific set of operations. Every C program consists of one or more functions, and every C program must contain a function called      main()—the reason being that a program will always start execution from the beginning of this function. So imagine that you’ve created, compiled, and linked a file calledprogname.exe. When you execute this program, it causes the functionmain()for the program to be called.

The first line of the definition for the functionmain()is as follows:

void main()           /* This identifies the function main() */

This defines the start of the functionmain(). Notice that there is no semicolon at the end of the line. The first line identifying this as the functionmain()has the keywordvoidat the beginning. What appears here defines the type of value to be returned by the function. The keywordvoidsignifies that the functionmain()returns no value.

There are circumstances in which you would want to return something frommain()to the operating system—an error code, for example. In those situations, a keyword other thanvoidwould be used. I’ll cover this in a later chapter.

The parentheses that immediately follow the name of the function,main, enclose a definition of what information is to be transferred tomain()when it starts executing. In this example, however, you can see that there’s nothing between the parentheses, so no information can be transferred. Later, you’ll see how information is transferred tomain()and to other functions in a program. In general, the functionmain()can call other functions that, in turn, may call further functions, and so on. For every function that’s called, you have the opportunity to pass some information to it within the parentheses that follow its name.

Keywords

In C, a keyword is a word with special significance, so you shouldn’t use keywords for any other purpose in your program. For this reason, keywords are also referred to as reserved words. In the preceding example,voidis a keyword. C has several keywords, and you’ll become familiar with more of them as you learn more of the language. You’ll find a complete list of C keywords in Appendix C.

Editing Your First Program in C

You could try altering the same program to display something else on the screen. For example, you might want to try editing the program to read like this:

/* Program 1.2 Your Second C Program */
#include<stdio.h>
void main()
{
  printf("If at first you don\'t succeed, try, try, try again!");
}

The\'sequence in the middle of the text to be displayed is called an escape sequence. Here it’s a special way of including a single quote in the text. Because single quotes are used to indicate where a character constant begins and ends, you need a special way to indicate when you mean a single quote and not the start of a character constant. You’ll learn more about escapes sequences very soon. You can try recompiling the program, relinking it, and running it again once you’ve altered the source. With a following wind, and a bit of luck, you’ve now edited your first program. You’ve written a program using the editor, edited it, and then compiled, linked, and executed it.

Dealing with Errors

To err is human, so there’s no need to be embarrassed about making mistakes. Fortunately, computers don’t generally make mistakes themselves and they’re actually very good at indicating where we’ve slipped up. Sooner or later your compiler is going to present you with a list (and sometimes a list that’s longer than you want) of the mistakes that are in your source code. You’ll usually get an indication of the statements that are in error. When this happens, you must return to the editing stage, find out what’s wrong with the incorrect code, and fix it. Keep in mind that one error can result in error messages for subsequent statements that may actually be correct. This usually happens with statements that refer to something that is supposed to be defined by a statement containing an error. Of course, if a statement that defines something has an error, then what was supposed to be defined won’t be.

Let’s step through what happens when your source code is incorrect by creating an error in a program. Edit your second program example, removing the semicolon (;) at the end of the line withprintf()in it, as shown here:

/* Program 1.2 Your Second C Program */ #include<stdio.h>
void main()
{
  printf("If at first you don\'t succeed, try, try, try again!")
}

If you now try to compile this program, you’ll see an error message that will vary slightly depending on which compiler you’re using. A typical error message is as follows:

----------------------------------------------------------------------Syntax error : missing ';' before '}'
HELLO.C - 1 error(s), 0 warning(s)
----------------------------------------------------------------------

Here, the compiler is able to determine precisely what the error is, and where. There really should be a semicolon at the end of thatprintf()line. As you start writing your own programs, you’ll probably get lots of errors during compilation that are caused by simple punctuation mistakes. It’s so easy to forget a comma or a bracket, or to just press the wrong key. Don’t worry about this: lots of experienced programmers make exactly the same mistakes—even after years of practice.

As I said earlier, just one mistake can sometimes result in a whole stream of abuse from your compiler, as it throws you a multitude of different things that it doesn’t like. Don’t get put off by the number of errors reported. After you consider the messages carefully, the basic approach is to go back and edit your source code to fix what you can, ignoring the errors that you can’t understand. Then try to compile the source file again. With luck, you’ll get fewer errors the next time around.

To correct your example program, just go back to your editor and reenter the semicolon. Recompile and check for any other errors, and your program is fit to be run again.

Creating Your First Program in C

It’s time to create your first program. Let’s step through the processes of creating a simple C program, from entering the program itself to executing the program. Don’t worry if what you type doesn’t mean anything to you at this stage—I’ll explain everything as we go along.


Figure 1-1.  Creating and executing a program

......................................................................................... 

Try It Out: An Example C Program

Run your editor and type in the following program exactly as it’s written. Be careful to input the punctuation exactly as you see here. The brackets used on the fourth and last lines are braces—the curly ones {}, not the square ones[]or the round ones()—it really does matter. Also, make sure you put the slashes the right way (/), as later you’ll be using the backslash (\) as well. Don’t forget the semicolon (;).

Run your editor and type in the following program exactly as it’s written. Be careful to input the punctuation exactly as you see here. The brackets used on the fourth and last lines are braces—the curly ones {}, not the square ones [] or the round ones ()—it really does matter. Also, make sure you put the slashes the right way (/), as later you’ll be using the backslash (\) as well. Don’t forget the semicolon (;).

/* Program 1.1 Your Very First C Program - Displaying Hello World */
#include <stdio.h>
void main()
{
  printf("Hello world");
}

When you’ve entered the preceding source code, save the program ashello.c. You can use whatever name you like instead ofhello, but the extension must be.c. This extension name is the common convention when you write C programs. The extension identifies the contents of the file as C source code. Most      compilers will expect the source file to have the extension.c, and if it doesn’t, the compiler may refuse to process it.

Now you’re ready to compile your program. Exactly how you do this will depend upon which compiler you’re using. If your C compiler allows you to work in an IDE, then you should easily be able to find your way to a menu where you can select the Compile option. In UNIX, the command you would use iscc.

Next, you’ll link all the pieces necessary to create an executable program. This will add in code from the standard libraries that your program needs. Once again, the precise way to do this will depend upon which compiler system you’re using. If you’re using UNIX, then append any modules that you need to include at the end of yourcccommand. In an IDE, you’ll find the Link option on one of the menus. Remember that many IDEs offer a Build option that will compile and link your program automatically. If you aren’t working in an IDE, you should again consult your documentation to find out what the command is to run the linker.

Finally, you can execute your program. Remember that you can do this in several ways. There is the usual method of double-clicking the.exefile from Windows Explorer if you’re using Windows. You could also run your program from the command line. To do so, just start a command-line session, change the current directory to the one that contains the.exefile for your program, and then enter the program name to run it. Within an IDE, you’ll probably also have the option of running your program directly. Alternatively, there may be a Run menu that will compile, link, and execute the program in one go.


NOTE 
If you’re working in an IDE, you may need to use the Window menu to change to an Output window, where you can see the results of your program execution.

If everything worked without producing any error messages, you’ve done it! This is your first program, and you should see the following message on the screen:

----------------------------------------------------------------------      Hello world
----------------------------------------------------------------------

 

........................................................................................

Programming in C

If you want to learn the fundamentals of C programming, you've come to the right place. This article is excerpted from the book Beginning C, third edition, written by Ivor Horton (Apress, 2004; ISBN: 1590592530).

C IS A POWERFUL AND COMPACT computer language that allows you to write programs that specify exactly what you want your computer to do. You’re in charge: you create a program, which is just a set of instructions, and your computer will follow those instructions.

Programming in C isn’t difficult, as you’re about to find out. I’m going to teach you all the fundamentals of C programming in an enjoyable and easy-to-understand way, and by the end of this chapter, you’ll have written your first few C programs. It’s as easy as that!

In this chapter you’ll learn

  1. How to create C programs
  2. How C programs are organized
  3. How to write your own program to display text on the screen

Creating C Programs

There are four fundamental stages, or processes, in the creation of any C program:

  1. Editing
  2. Compiling
  3. Linking
  4. Executing

You’ll soon know all these processes like the back of your hand (you’ll be doing them so easily and so often), but first let’s consider what each process is and how it contributes to the creation of a C program.

Editing

This is the process of creating and editing C source code—the name given to the program instructions you write. Some C compilers come with a specific editor that can provide a lot of assistance in managing your programs. In fact, an editor often provides a complete environment for writing, managing, developing, and testing your programs. This is sometimes called an integrated development environment, or IDE.

You can also use other editors to create your source files, but they must store the code as plain text without any extra formatting data embedded in it. In general, if you have a compiler system with an editor included, then it will provide a lot of features that make it easier to write and organize your source programs. There will usually be automatic facilities for laying out the program text appropriately and color highlighting for important language elements, which not only makes your code more readable, but also provides a clear indicator when you make errors in keying in such words.

If you’re working in UNIX, then the most common text editor is the vi editor. Alternately, you might prefer to use theemacs editor.

From a PC, you could use one the many freeware and shareware programming editors. These will often provide a lot of help in ensuring your code is correct with syntax highlighting and autoindenting of your code. Don’t use word processors such as Microsoft Word, as they aren’t suitable for producing program code.

Compiling

The compiler converts your source code into machine language, and detects and reports errors in the compilation process. The input to this stage is the file you produced during your editing, which is usually referred to as a source file.

The compiler can detect a wide range of errors that are due to invalid or unrecognized program code, as well as structural errors where, for example, part of a program can never be executed. The output from the compiler is known as object code and is stored in files called object files, which usually have names with the extension.obj. The compiler can detect several different kinds of errors during the translation process, and most of these will prevent the object file from being created.


NOTE
In UNIX, object files have the extension.o.

The result of a successful compilation is a file with the same name that you used for the source file, but with the.objextension.

If you’re working in UNIX, then the standard command to compile your C programs will be cc. You can use it like this:

cc -c myprog.c

wheremyprog.c is the program you want to compile. Note that if you omit the-oflag, your program will automatically be linked as well. If you’re using the GNU’s Not UNIX (GNU) compiler, you should type

gcc -c myprog.c.

The result of a successful compilation will be an object file.

Most C compilers will have a standard compile option, whether it’s from the command line (such ascc myprog.c) or a menu option from within an IDE (where you’ll find a Compile menu option).

Linking

The linker combines the various modules generated by the compiler from source code files, adds required code modules from program libraries supplied as part of C, and welds everything into an executable whole. The linker can also detect and report errors—for example, if part of your program is missing or a nonexistent library component is referenced.

In practice, if your program is of any significant size, it will consist of several separate source code files, which can then be linked. A large program may be difficult to write in one session. By breaking it up into a number of smaller source files, you can make the development of the program a whole lot easier. The source files can be compiled separately, which makes eliminating simple typographical errors a bit easier. Furthermore, the whole program can usually be developed incrementally. Each source file will have its own file name, and the set of source files that make up the program will usually be integrated under a project name, which is used to refer to the whole program.

Program libraries support and extend the C language by providing routines to carry out operations that aren’t part of the language. For example, libraries contain routines that support operations such as performing input and output, calculating a square root, comparing two character strings, or obtaining date and time information.

A failure during the linking phase means that, once again, you have to go back and edit your source code. Success, on the other hand, will produce an executable file. In a Microsoft Windows environment, this executable file will have the.exeextension; in UNIX, there will be no such extension, but the file will be of an executable type.

In UNIX, the modules that are to be linked are given together with thecccommand, for example:

cc myprog.c mod1.c mod2.o

These three modules will be linked. Notice that the last module here has the extension.o. This is because it has previously been compiled: the.oextension tells the compiler that the module is waiting to be linked and doesn’t need to be compiled again. The output of this stage is a file calleda.out, which you should then rename to something more meaningful.

An alternative form to this is as follows:

cc -o myprog myprog.c mod.c mod2.o

This will compile and link the modulemyprog.cand create an executable file calledmyprog(defined straight after the-oflag).

Many C compilers also have a Build option, which will compile and link your program in one step. This option will usually be found, within an IDE, in the Compile menu; alternatively, it may have a menu of its own.

Executing

The execution stage is when you run your program, having completed all the previous processes successfully. Unfortunately, this stage can also generate a wide variety of error conditions, ranging from producing the wrong output to sitting there and doing nothing, perhaps crashing your computer for good measure. In all cases, it’s back to the editing process to check your source code.

Now for the good news: this is the stage where, at last, you get to see your computer doing exactly what you told it to do!

In UNIX and DOS, to execute a program you just enter the name of the file that has been compiled and linked.

In most IDEs, you’ll find an appropriate menu command that allows you to Run or Execute your compiled program. This option may have a menu of its own, or you may find it under the Compile menu option.

In Windows, you can use Windows Explorer to locate the.exefile of your program, and then you can double-click the file.

The processes of editing, compiling, linking, and executing are essentially the same for developing programs in any environment and with any compiled language. Figure 1-1 summarizes how you would typically pass through each of these processes as you create your own C programs.