You are on page 1of 22

Learn C programming tutorial lesson 1 -

Hello World
What is C and why learn it
C was developed in the early 1970s by Dennis Ritchie at Bell Laboratories. C was originally
designed for writing system software but today a variety of software programs are written in C.
C can be used on many different types of computers but is mostly used with the UNIX operating
system.
It is a good idea to learn C because it has been around for a long time which means there is a lot
of information available on it. Quite a few other programming languages such as C++ and Java
are also based on C which means you will be able to learn them more easily in the future.
What you will need
This tutorial is written for both Windows and UNIX/Linux users. All the code in the examples
has been tested and works the same on both operating systems.
If you are using Windows then you need to download borland C++ compiler from
http://www.borland.com/cbuilder/cppcomp. Once you have downloaded and installed it you need
to add "C:\Borland\BCC55\Bin" to your path. To add it to your path in Windows 95/98/ME you
need to add the line "PATH=C:\Borland\BCC55\Bin" to c:\autoexec.bat using notepad. If you
are using Windows NT/2000/XP then you need to open the control panel and then double click
on "system". Click on the "Advanced" tab and then click "Environment Variables". Select the
item called "Path" and then click "Edit". Add ";C:\Borland\BCC55\Bin" to "Variable value" in
the dialog box that appears and then click Ok and close everything.
All Windows users will now have to create a text file called "bcc32.cfg" in
"C:\Borland\BCC55\Bin" and save the following lines of text in it:
-I"C:\Borland\BCC55\include"
-L"C:\Borland\BCC55\lib"
If you are using UNIX/Linux then you will most probably have a C compiler installed called
GCC. To check if you have it installed type "cc" at the command prompt. If for some reason you
don't have it then you can download it from http://gcc.gnu.org.
Your first program
The first thing we must do is open a text editor. Windows users can use Notepad and
UNIX/Linux users can use emacs or vi. Now type the following lines of code and then I will
explain it. Make sure that you type it exactly as I have or else you will have problems. Also don't
be scared if you think it is too complicated because it is all very easy once you understand it.
#include<stdio.h>

int main()
{
printf("Hello World\n");
return 0;
}
#include<stdio.h>
This includes a file called stdio.h which lets us use certain commands. stdio is short for Standard
Input/Output which means it has commands for input like reading from the keyboard and output
like printing things on the screen.
int main()
int is what is called the return value which will be explained in a while. main is the name of the
point where the program starts and the brackets are there for a reason that you will learn in the
future but they have to be there.
{}
The 2 curly brackets are used to group all the commands together so it is known that the
commands belong to main. These curly brackets are used very often in C to group things
together.
printf("Hello World\n");
This is the printf command and it prints text on the screen. The data that is to be printed is put
inside brackets. You will also notice that the words are inside inverted commas because they are
what is called a string. Each letter is called a character and a series of characters that is grouped
together is called a string. Strings must always be put between inverted commas. The \n is called
an escape sequence and represents a newline character and is used because when you press
ENTER it doesn't insert a new line character but instead takes you onto the next line in the text
editor. You have to put a semi-colon after every command to show that it is the end of the
command.
Table of commonly used escape sequences:
\a Audible signal
\b Backspace
\t Tab
\n Newline
\v Vertical tab
\f New page\Clear screen
\r Carriage return
return 0;
The int in int main() is short for integer which is another word for number. We need to use the
return command to return the value 0 to the operating system to tell it that there were no errors
while the program was running. Notice that it is a command so it also has to have a semi-colon
after it.
Save the text file as hello.c and if you are using Notepad make sure you select All Files from the
save dialog or else you won't be able to compile your program.
You now need to open a command prompt. If you are using Windows then click Start->Run and
type "command" and Click Ok. If you are using UNIX/Linux and are not using a graphical user
interface then you will have to exit the text editor.
Using the command prompt, change to the directory that you saved your file in. Windows users
must then type:
C:\>bcc32 hello.c
UNIX/Linux users must type:
$cc hello.c -ohello
The -o is for the output file name. If you leave out the -o then the file name a.out is used.
This will compile your C program. If you made any mistakes then it will tell you which line you
made it on and you will have to type out the code again and this time make sure you do it exactly
as I did it. If you did everything right then you will not see any error messages and your program
will have been compiled into an exe. You can now run this program by typing "hello.exe" for
Windows and "./hello" for UNIX/Linux.
You should now see the words "Hello World" printed on the screen. Congratulations! You have
just made your first program in C.
Indentation
You will see that the printf and return commands have been indented or moved away from the
left side. This is used to make the code more readable. It seems like a stupid thing to do because
it just wastes time but when you start writing longer, more complex programs, you will
understand why indentation is needed.
Using comments
Comments are a way of explaining what a program does. They are put after // or between /* */.
Comments are ignored by the compiler and are used by you and other people to understand your
code. You should always put a comment at the top of a program that tells you what the program
does because one day if you come back and look at a program you might not be able to
understand what it does but the comment will tell you. You can also use comments in between
your code to explain a piece of code that is very complex. Here is an example of how to
comment the Hello World program:
/* Author: Your name
Date: yyyy/mm/dd
Description:
Writes the words "Hello World" on the screen */

#include<stdio.h>

int main()
{
printf("Hello World\n"); //prints "Hello World"
return 0;
}

What are variables


Variables in C are memory locations that are given names and can be assigned values. We use
variables to store data in memory for later use. There are 2 basic kinds of variables in C which
are numeric and character.
Numeric variables
Numeric variables can either be integer values or they can be Real values. Integer values are
whole numbers without a fraction part or decimal point in them. Real numbers can have a
decimal point in them.
Character variables
Character variables are letters of the alphabet as well as all characters on the ASCII chart and
even the numbers 0 - 9. Characters must always be put between single quotes. A number put
between single quotes is not the same thing as a number without them.
What are constants
The difference between variables and constants is that variables can change their value at any
time but constants can never change their value. Constants can be useful for items such as Pi or
the charge on an electron. Using constants can stop you from changing the value of an item by
mistake.
Declaring variables
To declare a variable we first put the type of variable and then give the variable a name. The
following is a table of the names of the types of variables as well as their ranges:
Name Type Range
int Numeric - Integer -32 768 to 32 767
short Numeric - Integer -32 768 to 32 767
long Numeric - Integer -2 147 483 648 to 2 147 483 647
float Numeric - Real 1.2 X 10-38 to 3.4 X 1038
double Numeric - Real 2.2 X 10-308 to 1.8 X 10308
char Character All ASCII characters
You can name a variable anything you like as long as it includes only letters, numbers or
underscores and does not start with a number. It is a good idea to keep your variable names less
than 32 characters long to save time on typing them out and for compiler compatibility reasons.
Variables must always be declared at the top before any other commands are used. Now let's
declare an integer variable called a and a character variable called b.
int main()
{
int a;
char b;
return 0;
}
You can declare more than one variable at the same time in the following way:
int main()
{
int a,b,c;
return 0;
}
To declare a constant all you have to do it put the word const in front of a normal variable
declaration and make assign a value to it.
int main()
{
const float pi = 3.14;
return 0;
}

Signed and unsigned variables


The difference between signed and unsigned variables is that signed variables can be either
negative or positive but unsigned variables can only be positive. By using an unsigned variable
you can increase the maximum positive range. When you declare a variable in the normal way it
is automatically a signed variable. To declare an unsigned variable you just put the word
unsigned before your variable declaration or signed for a signed variable although there is no
reason to declare a variable as signed since they already are.
int main()
{
unsigned int a;
signed int b;
return 0;
}

Using variables in calculations


To assign a value to a variable you use the equals sign.
int main()
{
int a;
char b;
a = 3;
b = 'H';
return 0;
}
There are a few different operators that can be used when performing calculations which are
listed in the following table:
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus(Remainder of integer division)
To perform a calculation you need to have a variable to put the answer into. You can also use
both variables and normal numbers in calculations.
int main()
{
int a,b;
a = 5;
b = a + 3;
a = a - 3;
return 0;
}

Reading and printing variables


You can read a variable from the keyboard with the scanf command and print a variable with the
printf command.
#include<stdio.h>

int main()
{
int a;
scanf("%d",&a);
a = a * 2;
printf("The answer is %d",a);
return 0;
}
The %d is for reading or printing integer values and there are others as shown in the following
table:
%d or %i int
%c char
%f float
%lf double
%s string

The if statement
So far we have only learnt how to make programs that do one thing after the other without being
able to make decisions. The if statement can be used to test conditions so that we can alter the
flow of a program. The following example has the basic structure of an if statement:
#include<stdio.h>

int main()
{
int mark;
char pass;
scanf("%d",&mark);
if (mark > 40)
pass = 'y';
return 0;
}
In the above example the user enters the mark they got and then the if statement is used to test if
the mark is greater than 40. Make sure you remember to always put the conditions of the if
statement in brackets. If the mark is greater than 40 then it is a pass.
Now we must also test if the user has failed. We could do it by adding another if statement but
there is a better way which is to use the else statement that goes with the if statement.
#include<stdio.h>

int main()
{
int mark;
char pass;
scanf("%d",&mark);
if (mark > 40)
pass = 'y';
else
pass = 'n';
return 0;
}
The if statement first tests if a condition is true and then executes an instruction and the else is
for when the result of the condition is false.
If you want to execute more than 1 instruction in an if statement then you have to put them
between curly brackets. The curly brackets are used to group commands together.
#include<stdio.h>

int main()
{
int mark;
char pass;
scanf("%d",&mark);
if (mark > 40)
{
pass = 'y';
printf("You passed");
}
else
{
pass = 'n';
printf("You failed");
}
return 0;
}
It is possible to test 2 or more conditions at once using the AND (&&) operator. You can use the
OR (||) operator to test if 1 of 2 conditions is true. The NOT (!) operator makes a true result of a
test false and vice versa.
#include<stdio.h>

int main()
{
int a,b;
scanf("%d",&a);
scanf("%d",&b);
if (a > 0 && b > 0)
printf("Both numbers are positive\n");
if (a == 0 || b == 0)
printf("At least one of the numbers = 0\n");
if (!(a > 0) && !(b > 0))
printf("Both numbers are negative\n");
return 0;
}

Boolean operators
In the above examples we used > and < which are called boolean operators. They are called
boolean operators because they give you either true or false when you use them to test a
condition. The following is table of all the boolean operators in c:
== Equal
!= Not equal
> Greater than
>= Greater than or equal
< Less than
<= Less than or equal
&& And
|| Or
! Not

The switch statement


The switch statement is just like an if statement but it has many conditions and the commands for
those conditions in only 1 statement. It is runs faster than an if statement. In a switch statement
you first choose the variable to be tested and then you give each of the conditions and the
commands for the conditions. You can also put in a default if none of the conditions are equal to
the value of the variable. If you use more than one command then you need to remember to
group them between curly brackets.
#include<stdio.h>

int main()
{
char fruit;
printf("Which one is your favourite fruit:\n");
printf("a) Apples\n");
printf("b) Bananas\n");
printf("c) Cherries\n");
scanf("%c",&fruit);
switch (fruit)
{
case 'a':
printf("You like apples\n");
break;
case 'b':
printf("You like bananas\n");
break;
case 'c':
printf("You like cherries\n");
break;
default:
printf("You entered an invalid choice\n");
}
return 0;
}
What are loops
Sometimes you will want to do something a lot of times. An example would be printing a
character at the beginning of each line on the screen. To do this you would have to type out 24
printf commands because there are 25 rows on the screen and the 25th row will be left blank. We
can use a loop to do this for us and only have to type 1 printf command. There are 3 basic types
of loops which are the for loop, while loop and do while loop.
The for loop
The for loop lets you loop from one number to another number and increases by a specified
number each time. This loop is best suited for the above problem because we know exactly how
many times we need to loop for. The for loop uses the following structure:
for (starting number;loop condition;increase variable)
command;
With loops you also have to put commands between curly brackets if there is more than one of
them. Here is the solution to the problem that we had with the 24 printf commands:
#include

int main()
{
int i;
for (i = 1;i <= 24;i++)
printf("H\n");
return 0;
}
A for loop is made up of 3 parts inside its brackets which are separated by semi-colons. The first
part initializes the loop variable. The loop variable controls and counts the number of times a
loop runs. In the example the loop variable is called i and is initialized to 1. The second part of
the for loop is the condition a loop must meet to keep running. In the example the loop will run
while i is less than or equal to 24 or in other words it will run 24 times. The third part is the loop
variable incrementer. In the example i++ has been used which is the same as saying i = i + 1.
This is called incrementing. Each time the loop runs i has 1 added to it. It is also possible to use
i-- to subtract 1 from a variable in which case it's called decrementing.
The while loop
The while loop is different from the for loop because it is used when you don't know how many
times you want the loop to run. You also have to always make sure you initialize the loop
variable before you enter the loop. Another thing you have to do is increment the variable inside
the loop. Here is an example of a while loop that runs the amount of times that the user enters:
#include<stdio.h>

int main()
{
int i,times;
scanf("%d",&times);
i = 0;
while (i <= times)
{
i++;
printf("%d\n",i);
}
return 0;
}

The do while loop


The do while loop is the same as the while loop except that it tests the condition at the bottom of
the loop.
#include<stdio.h>

int main()
{
int i,times;
scanf("%d",&times);
i = 0;
do
{
i++;
printf("%d\n",i);
}
while (i <= times);
return 0;
}

Break and continue


You can exit out of a loop at any time using the break statement. This is useful when you want a
loop to stop running because a condition has been met other than the loop end condition.
#include<stdio.h>

int main()
{
int i;
while (i < 10)
{
i++;
if (i == 5)
break;
}
return 0;
}
You can use continue to skip the rest of the current loop and start from the top again while
incrementing the loop variable again. The following example will never print "Hello" because of
the continue.
#include<stdio.h>

int main()
{
int i;
while (i < 10)
{
i++;
continue;
printf("Hello\n");
}
return 0;
}

What are pointers


A pointer is a variable that holds a memory address. Because it holds a memory address it is said
to be pointing to the value at that memory location. You can use a pointer in a certain way to get
the value at the address to which it points.
Pointers can be either typed or untyped. A typed pointer points to a particular variable type such
as an integer. An untyped pointer points to any data type.
To declare a pointer you must put a * in front of its name. Here is an examaple of how to declare
a pointer to an integer and an untyped pointer:
int main()
{
int *p;
void *up;
return 0;
}
You can put the address of an integer into a pointer to an integer by using the & operator to get
the integer's address.
int main()
{
int i;
int *p;
i = 5;
p = &i;
return 0;
}
You can access the value of the integer that is being pointed to by dereferencing the pointer. The
* is used to dereference a pointer. Changing the value pointed to by the integer will change the
value of the integer.
int main()
{
int i,j;
int *p;
i = 5;
p = &i;
j = *p; //j = i
*p = 7; //i = 7
return 0;
}
Using pointers in the above way is just a long way of saying j = i. You will find out about much
more useful ways to use pointers later on but for now it is only important that you have a basic
idea of how they work.

Learn C programming tutorial lesson 6 -


Arrays
Up until now if you wanted to declare 5 variables you would have to do something like this:
int i1,i2,i3,i4,i5;
What if you wanted to declare 100 variables? That would take quite a long time. If you use an
array on the other hand then you can declare as many variables as you want with only 1 variable
name.
An array is declared in the same way as a normal variable except that you must put square
brackets after the variable name. You must also put the amount of elements you want in the array
in these sqaure brackets.
int a[5];
To access the value of an element of an array you must again use the square brackets but with the
number of the element you want to access. When accessing an element of an array you must
remember that they start from 0 and not 1. This means that an array which has 5 elements has an
element range of 0 to 4.
int a[5];
a[0] = 12;
a[1] = 23;
a[2] = 34;
a[3] = 45;
a[4] = 56;
printf("%d",a[0]);

Using arrays with loops


The most useful thing to do with an array is use it in a loop. This is because the element number
follow a sequence just like a loop does.
When an array is declared the values are not set to 0 automatically. You will sometimes want to
set the values of all elements to 0. This is called initializing the array. Here is an example of how
to initialize an array of 10 elements using a for loop:
int a[10];
for (i = 0;i < 10;i++)
a[i] = 0;

Multi-dimensional arrays
The arrays we have been using so far are called 1-dimensional arrays because they only have
what can be thought of a 1 column of elements. 2-dimensional arrays have rows and columns.
Here is a picture which explains it better:
1-dimensional array
01
12
23
2-dimensional array
012
0123
1456
2789
You do get 3-dimensional arrays and more but they are not used as often. Here is an example of
how you declare a 2-dimensional array and how to use it. This example uses 2 loops because it
has to go through both rows and columns.
int a[3][3],i,j;
for (i = 0;i < 3;i++)
for (j = 0;j < 3;j++)
a[i][j] = 0;

Learn C programming tutorial lesson 7 -


Strings
A string is an array of characters. Strings must have a 0 or null character after the last character
to show where the string ends. The null character is not included in the string.
There are 2 ways of using strings. The first is with a character array and the second is with a
string pointer.
A character array is declared in the same way as a normal array.
char ca[10];
You must set the value of each individual element of the array to the character you want and you
must make the last character a 0. Remember to use %s when printing the string.
char ca[10];
ca[0] = 'H';
ca[1] = 'e';
ca[2] = 'l';
ca[3] = 'l';
ca[4] = 'o';
ca[5] = 0;
printf("%s",ca);
String pointers are declared as a pointer to a char.
char *sp;
When you assign a value to the string pointer it will automatically put the 0 in for you unlike
character arrays.
char *sp;
sp = "Hello";
printf("%s",sp);
You can read a string into only a character array using scanf and not a string pointer. If you want
to read into a string pointer then you must make it point to a character array.
char ca[10],*sp;
scanf("%s",ca);
sp = ca;
scanf("%s",sp);

String handling functions


The strings.h header file has some useful functions for working with strings. Here are some of
the functions you will use most often:
strcpy(destination,source)
You can't just use string1 = string2 in C. You have to use the strcpy function to copy one string
to another. strcpy copies the source string to the destination string.
s1 = "abc";
s2 = "xyz";
strcpy(s1,s2); // s1 = "xyz"
strcat(destination,source)
Joins the destination and source strings and puts the joined string into the destination string.
s1 = "abc";
s2 = "xyz";
strcat(s1,s2); // s1 = "abcxyz"
strcmp(first,second)
Compares the first and second strings. If the first string is greater than the second one then a
number higher than 0 is returned. If the first string is less than the second then a number lower
than 0 is returned. If the strings are equal then 0 is returned.
s1 = "abc";
s2 = "abc";
i = strcmp(s1,s2); // i = 0
strlen(string)
Returns the amount of characters in a string.
s = "abcde";
i = strlen(s); // i = 5

Learn C programming tutorial lesson 8 -


Functions
Functions are sub-programs. You have already been using a function which is the main function.
You must always declare a function before the function that calls it. The main function will be
calling our function so we will put ours above main.
First put its return value such as int or char. If you don't want a return value then use void. After
that give it a unique name and put a set of brackets after that. You then put the set of curly
brackets which will have the sub-program between them. We will call our function Hello
because it will simply print the word Hello on the screen.
#include<stdio.h>
void Hello()
{
printf("Hello\n");
}

int main()
{
Hello();
return 0;
}

Parameters
Parameters are values that are given to a function so that it can perform calculations with them.
The "Hello\n" which we used in the Hello function is a parameter which has been passed to the
printf function.
You need to declare variables inside the parameter brackets to store the values of the parameters
that are passed to the function. Here is an Add function which adds the 2 parameters together and
then returns the result.
#include<stdio.h>

int Add(int a,int b)


{
return a + b;
}

int main()
{
int answer;
answer = Add(5,7);
return 0;
}
You can pass the address of a variable to a function so that a copy isn't made. For this you need a
pointer.
#include<stdio.h>

int Add(int *a,int *b)


{
return *a + *b;
}

int main()
{
int answer;
int num1 = 5;
int num2 = 7;
answer = Add(&num1,&num2);
printf("%d\n",answer);
return 0;
}

Global and local variables


A local variable is one that is declared inside a function and can only be used by that function. If
you declare a variable outside all functions then it is a global variable and can be used by all
functions in a program.
#include<stdio.h>

// Global variables
int a;
int b;

int Add()
{
return a + b;
}

int main()
{
int answer; // Local variable
a = 5;
b = 7;
answer = Add();
printf("%d\n",answer);
return 0;
}

Command-line parameters
Sometimes you also pass parameters from the command-line to your program. Here is an
example:
$ myprogram -A
To be able to access the command line parameters you have to declare variables for them in the
brackets of the main function. The first parameter is the number of arguements passed. The name
of the program also counts as a parameter and is parameter 0. The second parameter is the
arguements in a string array.
#include<stdio.h>

int main(int argc,char *argv[])


{
int i;
printf("Amount: %d\n",argc);
if (argc > 0)
{
printf("Parameters:\n");
for (i = 0;i < argc;i++)
printf("%s\n",argv[i]);
}
return 0;
}
Learn C programming tutorial lesson 9 -
Structures
We already know that arrays are many variables of the same type grouped together under the
same name. Structures are like arrays except that they allow many variables of different types
grouped together under the same name. For example you can create a structure called person
which is made up of a string for the name and an integer for the age. Here is how you would
create that person structure in C:
struct person
{
char *name;
int age;
};
The above is just a declaration of a type. You must still create a variable of that type to be able to
use it. Here is how you create a variable called p of the type person:
#include<stdio.h>

struct person
{
char *name;
int age;
};

int main()
{
struct person p;
return 0;
}
To access the string or integer of the structure you must use a dot between the structure name and
the variable name.
#include<stdio.h>

struct person
{
char *name;
int age;
};

int main()
{
struct person p;
p.name = "John Smith";
p.age = 25;
printf("%s",p.name);
printf("%d",p.age);
return 0;
}

Type definitions
You can give your own name to a variable using a type definition. Here is an example of how to
create a type definition called intptr for a pointer to an integer.
#include<stdio.h>

typedef int *intptr;

int main()
{
intptr ip;
return 0;
}

Type definitions for a structure


If you don't like to use the word struct when declaring a structure variable then you can create a
type definition for the structure. The name of the type definition of a structure is usually all in
uppercase letters.
#include<stdio.h>

typedef struct person


{
char *name;
int age;
} PERSON;

int main()
{
PERSON p;
p.name = "John Smith";
p.age = 25;
printf("%s",p.name);
printf("%d",p.age);
return 0;
}

Pointers to structures
When you use a pointer to a structure you must use -> instead of a dot.
#include<stdio.h>

typedef struct person


{
char *name;
int age;
} PERSON;

int main()
{
PERSON p;
PERSON *pptr;
PERSON pptr = &p;
pptr->name = "John Smith";
pptr->age = 25;
printf("%s",pptr->name);
printf("%d",pptr->age);
return 0;
}

Unions
Unions are like structures except they use less memory. If you create a structure with a double
that is 8 bytes and an integer that is 4 bytes then the total size will still only be 8 bytes. This is
because they are on top of each other. If you change the value of the double then the value of the
integer will change and if you change the value of the integer then the value of the double will
change. Here is an example of how to declare and use a union:
#include<stdio.h>

typedef union num


{
double d;
int i;
} NUM;

int main()
{
NUM n;
n.d = 3.14;
n.i = 5;
return 0;
}

Learn C programming tutorial lesson 10 -


Text and data files
Files let you store data on secondary storage such as a hard disk so that your programs can later
retrieve that data again. There are 2 types of files which are text files and data files.
Text files
Text files are used for storing character strings in a file. To create a text file you must first
declare a file pointer.
#include<stdio.h>

int main()
{
FILE *f;
return 0;
}
You must then open the file using the fopen function. fopen takes 2 parameters which are the file
name and the open mode. fopen returns a file pointer which we will assign to the file pointer
called f.
#include<stdio.h>

int main()
{
FILE *f;
f = fopen("test.txt","w");
return 0;
}
The above example will create a file called test.txt. The "w" means that the file is being opened
for writing and if the file does not exist then it will be created. Here are some other open modes:
r Open for reading
r+ Open for reading and writing
w Open for writing and create the file if it does not exist. If the file exists then make it blank.
Open for reading and writing and create the file if it does not exist. If the file exists then make
w+
it blank.
a Open for appending(writing at the end of file) and create the file if it does not exist.
a+ Open for reading and appending and create the file if it does not exist.
To write a string to the file you must use the fprintf command. fprintf is just like printf except
that you must use the file pointer as the first parameter.
#include<stdio.h>

int main()
{
FILE *f;
f = fopen("test.txt","w");
fprintf(f,"Hello");
return 0;
}
When you are finished using a file you must always close it. If you do not close a file then some
of the data might not be written to it. Use the fclose commmand to close a file.
#include<stdio.h>

int main()
{
FILE *f;
f = fopen("test.txt","w");
fprintf(f,"Hello");
fclose(f);
return 0;
}
The fgets command is used when reading from a text file. You must first declare a character
array as a buffer to store the string that is read from the file. The 3 parameters for fgets are the
buffer variable, the size of the buffer and the file pointer.
#include<stdio.h>

int main()
{
FILE *f;
char buf[100];
f = fopen("test.txt","r");
fgets(buf,sizeof(buf),f);
fclose(f);
printf("%s\n",buf);
return 0;
}
Data files
A data file is used to store types of data such as integers. When you open a data file you must
add the letter b to the open mode parameter of fopen.
#include<stdio.h>

int main()
{
FILE *f;
f = fopen("test.dat","wb");
fclose(f);
return 0;
}
fwrite is used to write to a file. The first parameter of fwrite is a pointer to the variable that you
want to write to the file. The second parameter is the size of the variable that must e written. The
third parameter is the number of variables to be written. The fourth parameter is the file pointer
of the file you want to write to.
#include<stdio.h>

int main()
{
FILE *f;
int buf;
f = fopen("test.dat","wb");
buf = 100;
fwrite(&buf,sizeof(buf),1,f);
fclose(f);
return 0;
}
fread is used to read from a file and is the same as fwrite except that the data is read into the
variable instead of writing from it. You must remember to change the file mode to read.
#include<stdio.h>

int main()
{
FILE *f;
int buf;
f = fopen("test.dat","rb");
fread(&buf,sizeof(buf),1,f);
printf("%d\n",buf);
fclose(f);
return 0;
}

Data files using structures


You can read and write structures to data files in the same way as you do with any other data
type. Here is an example:
#include<stdio.h>

struct
{
char name[100];
int age;
} p;

int main()
{
FILE *f;
strcpy(p.name,"John");
p.age = 25;
f = fopen("test.dat","wb");
fwrite(&p,1,sizeof(p),f);
fclose(f);
return 0;
}

You might also like