This page provides basic reference information on the C language.
It should be considered for reference only and not a substitute for attending class.
Declare variables at the beginning of a function (like main()) just after the opening curly bracket or brace ({). Variable declarations consist of the data type followed by a name for the variable. Variable names may consist of any of the upper or lower case letters, any of the digits (0..9) or the dash (-) or underscore (_) characters. Variable names may not begin with a digit.
The printf() function is used to display text on the screen. The basic format of a call
to the printf() function is printf, an opening parentheses (,
a string in quotes which may contain optional format specifiers or
special printing characters, and an optional list of variables
whose values are to be printed in the corresponding locations of the format specifiers:
Format specifiers are used in the printf() function to indicate where the values stored
in variables are to be printed and what the data type of the variable is. Each is preceeded
by a percent sign (%) in the string portion of a printf() command. The available format
specifiers are:
%d -- print/input a signed integer variable
(short or int).
%ld -- print/input a signed integer variable (long).
%f -- print/input a floating point variable (float).
%lf -- print/input a floating point variable (double).
%u -- print/input an unsigned integer variable.
%o -- print/input an unsigned integer variable in octal (base 8) format.
%x or X -- print/input an unsigned integer variable in
hexadecimal (base 16) format.
%E or E -- print/input a float or double in scientific
(exponential notation)
%c -- print/inputa character(char) variable
%s -- print/input a character array (string).
%% -- print/input the '%' character.
Format specifiers also allow you to include additional formatting information including: (1) field width (number of spaces to print the variable in), (2) number of positions to the right of the decimal point, (3) print numeric data with signs (+ or -, remember the - will always be included for negative numbers), and (4) left or right justify the printed data in the specified field width.
The following statements declare the variables used in the examples below:Special characters may be included in printf() strings. These include the following:
\n -- newline
\r -- carriage return
\t -- horizontal tab
\\ -- backslash
\' -- single quote
\" -- double quote
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulus (remainder after an integer division, i.e. 5 % 2 = 1 |
++ | Increment operator. Adds 1 to a variable, i.e. ++myVar or myVar++. If placed before the variable name the variable is pre-incremented (incremented before being used). If placed after the name of the variable the variable is post-incremented (incremented after being used). This operator can only be used with integer variables (short, int, long). |
-- | Decrement operator. Subtracts 1 to a variable, i.e. --myVar or myVar--. If placed before the variable name the variable is pre-decremented (decremented before being used). If placed after the name of the variable the variable is post-decremented (decremented after being used). This operator can only be used with integer variables (short, int, long). |
Logical operators are used in C to make decisions in if statements and in loop controls:
== | Is equal to. Example: if(X == 3) |
> | Is greater than. Example: if(X > 3) |
< | Is less than. Example: if(X < 3) |
>= | Is greater than or equal. Example: if(X >= 3) |
<= | Is less than or equal. Example: if(X <= 3) |
!= | Is not equal. Example: if(X != 3) |
while loops
Use a while loop when the
number of times the loop is to be repeated depends on some condition which changes
inside the loop. The basic structure of the while loop:
while(condition)
Example:
{
/* list of commands */
}
x = 0; /* Assume int x; has been declared */
while(x < 10)
{
printf("x = %d", x); /* print the current value of x */
x++; /* increment x */
}
for loops
Use a for loop when the number of times the loop is to be repeated is
known in advance. This may be a value known at the beginning of the program run or it
may be stored in an integer variable. The basic structure of the for loop
consists of (1) a loop counter initiation (i=0), (2) a condition which will terminate
the loop when it become FALSE (i<10), and (3) an increment statement (i++) :
for(initialization; condition; increment)
Example:
{
/* list of commands */
}
/* Assume int i; has been declared */
for(i = 0; i < 10; i++)
{
printf("i = %d", i); /* print the current value of i */
}
do...while loops
Use a do...while loop in the exact same way you would a while loop.
The important difference is that a do...while loop checks the loop termination
condition at the end of the loop. This means that a do...while loop will always
execute at lease once. The basic structure of the do...while :
do
Example:
{
while(x < 10);
/* list of commands */
}
x = 0; /* Assume int x; has been declared */
do
{
while(x < 10);
printf("x = %d", x); /* print the current value of x */
x++; /* increment x */
}
return_type FunctionName ( argument_list ) {
function code
}
A prototype is essentially the heading of a function definition, ending with a semi-colon (;), which is placed at the beginning of the source code or in a separate header file. The prototype should be placed in the code where it will be one of the first items read by the compiler. The purpose of the prototype is to allow give the compiler the function name, it's arguments and types, and it's return type so the compiler can check the syntax of any calls to the function during the compile process.
Some examples of prototypes:char func(void); int func(int x, float f); double func(char x[], float f); void func(double d, int x, char s[]);
All file operations consist of a 3-step process:
Step 1: Declare a pointer to a file: FILE *fptr; FILE is defined inas are all the related file functions. Step 2: Open the file by calling fopen(filename, mode). fopen() takes a file name, and a mode (read, write, append) as arguments. It returns a pointer to type FILE. This pointer is used for all file I/O. fptr = fopen("MyFile", "r"); /* Opens the file "MyFile" for reading */ fprt= fopen(filename, "w"); /* Opens the file whose name is stored */ /* in the character array filename for writing */ fopen(): 1. Returns a pointer to type FILE. 2. Arguments are 2 character strings a. filename - the name of the file to open as it appears in the disk directory. b. mode - a character string not a single character. This indicates how you intend to open the file. 1. "r" = read - file must already exist. 2. "w" = write - If the file exists its contents will be overwritten. If not it will be created. 3. "a" = append - New data will be appended to the end of the present data in the file if the file exists, otherwise the file will be created. 4. "r+" = read & write - file must already exist. 5. "w+" = read & write - if the file exists its contents are overwritten. If not it is created. 6. "a+" = read & append - if file does not exist it is created. Most programmers use just "r", "w" or "a" and do the read and write operations in separate functions each of which opens and closes the file. This is safer than leaving a file open while doing other things. Data can be read and written in text(default) or binary mode. If using binary mode you use: "rb" = read binary "wb" = write binary "ab" = append binary
The most straight forward way to open a file is: FILE *fptr; fptr = fopen("myfile.txt", "r"); But, this works fine as long as the file already exists. If not you are in trouble, so a safer way of opening a file is to check to see if it already exists first: if ( (fptr=fopen("myfile.txt","r"))==NULL) { printf("Can't open file myfile.txt\n"); exit(); } Use this statement in a function when you want to open the file. This opens the file for reading, but if the file doesn't exist it handles that problem. If you are opening the file for writing you don't have this problem as the file will be created if it does not exist. NOTE: If you want to avoid overwriting a file that already exists you can do the check for !=NULL and if the result is true give a warning that the file already exists.
fclose(fptr); This is the same for any type of file I/O
String I/O - reads and writes whole strings to a file. Functions: int fputs(const char*, FILE *); - writes a string to a file char *fgets(char *s, int n, FILE *); - reads a string from a file fgets(string, 80, fptr); - reads at most n-1 characters into char array s and terminates it with a '\0'. NOTE: The newline character '\n' is read in as part of the string and must be removed Example 1: Write strings typed at the keyboard. Terminates when a single [Return] is typed. #includemain() { FILE *ptr; char string[81]; /* Use 80 char lines */ fptr = fopen("textfile.txt","w"); while (strlen(gets(string)) > 0) { fputs(string, fptr); /* write string */ fputs("\n", fptr); /* write newline */ } fclose(fptr); } Note the use of the string input function gets(). Note also that the '\0' is not written to the file so we put in a newline character to separate the strings. Example 2: Read strings from file and write them to the screen. #include main() { FILE *ptr; char string[81]; /* Use 80 char lines */ if((fptr=fopen("textfile.txt","r"))==NULL) { printf("Can't open textfile.txt.\n"); exit(); } while (fgets(string,80,fptr) != NULL) { string[strlen(string)-1] = '\0'; /* Remove '\n' */ printf("%s\n", string); } fclose(fptr); } Note the explicit removal of the newline character from the string
Character I/O - data is read or written one character at a time. Functions: char getc(FILE *); - reads one character from a file char putc(int, FILE *); - writes one character to a file. Note the character is treated as an integer. Example 1: Reads characters from the keyboard and writes them to a file until a carriage return is pressed. #includemain() { FILE *ptr; /* pointer to FILE */ char ch; fptr=fopen("textfile.txt","w"); while ( (ch=getche()) != '\r') putc(ch, fptr); fclose(fptr); { Notice that we aren't checking to see if the file exists. We will create or overwrite it anyway. Example 2: Reads characters from a file and writes them to the screen. #include main() { FILE *ptr; /* pointer to FILE */ char ch; if( (fptr=fopen("textfile.txt","r")) == NULL) { printf("Can't open textfile.txt.\n"); exit(); } while ( (ch=getc(fptr)) != EOF) printf("%c", ch); fclose(fptr); { Note: EOF = -1, this is not a character stored on the disk. It is a flag transmitted by the operating system when it realizes it has read the last character in a file. Since all ASCII characters have an integer value of 0-255 -1 is unique and can be recognized as EOF. This is also why ch is read by getc() as an int type not a char type. Formatted I/O - Read/write formatted data like scanf() and printf() Functions: fprintf(ptr,"format specifier", varlist); - writes specified variables to disk fscanf(ptr,"format specifier", varlist); - reads specified variables from disk Warning: You have to remember the order and format of the data in order to read it back out in a meaningful form. Example 1: Reads an int, float, and string from the keyboard and writes them to disk. Terminate with 2 dummy numbers and null string #include main() { int inum; float fnum; char string[81]; FILE *fptr; fptr = fopen("textfile.txt", "w'); do { printf("Type int, float, and string: "); scanf("%d %f %s", &inum, &fnum, string); fprintf(fptr,"%d %f %s",inum,fnum,string); } while (strlen(string) > 0); fclose(fptr); } Example 2: Reads data back from textfile.txt #include main() { int inum; float fnum; char string[81]; FILE *fptr; if((fptr=fopen("textfile.txt","r'))==NULL); } printf("Can't open textfile.txt.\n"); exit(); } while(fscanf (fptr,"%d %f %s", &inum, &fnum, string) != EOF) printf("%d %f %s",inum,fnum,string); fclose(fptr); } Record (binary) - reads and writes structures and arrays to disk. Allows the reading and writing of large blocks of data at one time. Functions: fread(&object, sizeof(object), n, fptr); Reads n blocks of size sizeof(object) into object. Unless object is an array n=1. fwrite(&object, sizeof(object), n, fptr); Writes n objects of size sizeof(object) starting at &object. Example 1: Reads simple structures from keyboard and writes to disk. #include main() { struct simple /* Define a structure */ { int num; char ch; } sim; FILE *fptr; fptr=fopen("strufile.bin", "wb"); do { printf("Type an int and a char.\n"); scanf("%d %c", &sim.num,&sim.ch); fwrite(&sim, sizeof(struct simple),1,fptr); printf("Add another structure to disk(y/n)?"); } while(getche()=='y'); fclose(fptr); } Example 2: Reads simple structures from disk and prints to screen. #include main() { struct simple /* Define a structure */ { int num; char ch; } sim; FILE *fptr; if( (fptr=fopen("strufile.bin", "rb"))==NULL) { printf("Can't open strufile.bin.\n"); exit(); } while (fread(&sim, sizeof(struct simple),1, fptr)==1) printf("%d %c\n.",sim.num,sim.ch); fclose(fptr); } Note: fread() returns an integer value equal to the number of blocks read, ie. if we ask for one structure and fread() returns 0 we know we have reached the end of the file.