C Programming Language
C Programming Language
LECTURE NOTES
Halil Özmen
Purpose: These lecture notes are intended for the instructor. It is not a replacement for the notes
taken by the students in the classroom. The students can use these notes as a
complement to their own notes and to the text-book.
Table of Contents
1. C Programming Language Basics.............................................................................................. 2
2. Control Structures ...................................................................................................................... 4
2.1. Selection Structures .............................................................................................................. 5
2.2. Loop Statements................................................................................................................... 8
2.2.1. for loops ..................................................................................................................... 8
2.2.2. Conditional loops: while loops, do ... while loops ........................................................ 9
3. Modular Programming and Functions ...................................................................................... 12
3.1. Basics of Modular Programming ......................................................................................... 12
3.2. Function Definitions and Calling Functions ......................................................................... 12
3.3. Functions with no parameters ............................................................................................. 13
3.4. Functions with parameters .................................................................................................. 13
3.5. Functions that does not return value ................................................................................... 13
3.6. Functions that return value.................................................................................................. 14
3.7. Scope of variables .............................................................................................................. 15
4. Arrays ...................................................................................................................................... 16
4.1. One dimensional arrays ...................................................................................................... 16
4.2. Utilization of array elements ................................................................................................ 16
4.3. Input/Output of Arrays ......................................................................................................... 17
4.4. Array manipulation .............................................................................................................. 17
4.5. Arrays as function parameters ............................................................................................ 18
4.6. Two or more dimensional arrays ......................................................................................... 19
5. Strings ..................................................................................................................................... 21
5.1. String Basics ....................................................................................................................... 21
5.2. String Functions .................................................................................................................. 22
5.3. Character Analysis and Conversion: ................................................................................... 24
6. Structures ................................................................................................................................ 28
7. Pointers ................................................................................................................................... 33
7.1. Pointer Basics ..................................................................................................................... 33
7.2. Dynamic Memory Allocation................................................................................................ 34
7.3. Linked Lists......................................................................................................................... 35
8. Files ......................................................................................................................................... 37
9. Bit Manipulation ....................................................................................................................... 40
10. System Calls ............................................................................................................................ 41
10.1. Directory and File Manipulation System Calls.................................................................. 41
10.2. Date and Time System Calls ........................................................................................... 42
1. C Programming Language Basics
Data representation:
• constants
• variables
Constants:
• Integer constants: 7 248 -74 0 4 -1444
• Character constants: 'A' 'k' '.' '+' '4' '?' '\t' '\n'
• Float and double constants: 3.14159 0.00508 12345.0 15.0e4 15.0e-4 3.24e-04
Constant Definitions: #define PI 3.14159265358979323846264338
#define MAXSIZE 100
Variables:
Variables in programming languages are entities that hold values. The value that variables hold
may be changed.
Variable names must start with a-z, A-Z, and underscore "_", followed by a-z A-Z 0-9 _.
Valid variable names: a k total a6y x45_t4 ali ankara city06 _err
Invalid variables: 2abc ali-top abba.go pi3.14
Declaration:
int a;
char c1;
double x;
Assignment Statement:
a = 12;
ali = count;
a_0 = j2 + 16;
x = (j2 * 4) + (count / (j - 1) );
Arithmetic Operators:
+ - * / %
Arithmetic Expressions:
j2 * 4 + count / (j - 1)
a + b * c / d - e / f * g (what is the sequence of operations)
a + b * c / (d - e / f) * g (what is the sequence of operations)
Input / Output:
To use input and output functions, stdio.h must be included. The following line has to be put in
source file:
#include <stdio.h>
Input:
scanf("%d", &n); // Scanf reads things separated by whitespaces
scanf("%c", &c); // Input character
scanf("%f", &x); // Input float (or double)
scanf("%lf", &dist); // Input double
scanf("%d %c", &a, &b); // the 2 values can be on different
lines!
Output
printf("Enter a number: "); // Output just a string
printf("Total is %d\n", total); // Output string and an integer
Formatted Input/Output,
printf("Today is %02d/%02d/%4d\n", day, month, year);
printf("Height: %5.2f m., Weight: %10.4f gr.\n", height, weight);
Placeholders
Data type Placeholder Input example Output example
int %d scanf("%d", &val); printf("%d", val);
char %c scanf("%c", &letter1); printf("%c", letter1);
float %f scanf("%f", &kms); printf("%f", kms);
double %lf %f scanf("%lf", &height); printf("%f", height);
%d %4d %04d %-4d
%f %.4f %10.6f %lf %.4lf %10.2lf
C Programming Language 3 Halil Özmen
Built-in Functions
printf, scanf
other input and output functions
mathematical functions (sqrt, abs, sin, etc.), string functions, date and time functions, etc...
Exercises:
• Input an integer, output its square, cube and square-root.
• Input a distance (int km) and a speed (int), output duration in terms of hour:minute (hh:mm).
2. Control Structures
Control structures:
Control structures control the flow of execution in a program or function.
Compound statement:
Compound statement is a group of statements bracketed by { and } that are executed
sequentially.
{
statement1;
statement2;
. . .
statementn;
}
Conditions:
Condition is an expression that is either true (usually represented by 1) or false (represented by
0).
A condition or logical expression is an expression that can only take the values true or false.
A simple form of logical expression is the relational expression.
Relational operators:
Relational Operator Meaning Example
== equal to a == 7
!= not equal to b != total
> greater than height > 200.0
>= greater than or equal to points >= 20
< less than uptime < 99.5
<= less than or equal to quantity <= 100
Logical operators:
Logical Operator Meaning Example
&& and a > 4 && x == 20.7
|| or a > 4 || x == 20.7
! not !(a > 4 && x == 20.7)
if (condition) if (condition)
{ {
statement(s)...; statement1;
} statement2;
else . . .
{ statementn;
statement(s)...; }
} else
{
Examples: statement1;
if (height > 200) statement2;
{ . . .
printf("Tall\n"); statementm;
n_tall++; }
}
Nested if statements:
Sample cases:
Concept: if statements within if statements
Example-1 for Case:
Male, <20 years of age
Examples:
if (condition1) Male, >=20 years of age
{ Female, <20 years of age
statement(s)...; // optional Female, >=20 years of age
if (condition2)
{ Example-2 for Case:
statement(s)...; Temperature < -10
} -10 <= Temperature < 0
else 0 <= Temperature < 10
{ 10 <= Temperature < 20
statement(s)...; Temperature >= 20
}
statement(s)...; // optional
}
else
{
statement(s)...; // optional
if (condition3) // may be: if (condition2)
{
statement(s)...;
}
else
{
statement(s)...;
}
statement(s)...; // optional
}
Example:
if (gender == 'M')
{
if (age > 20)
{
...
}
else
{
...
}
}
else
{
if (age > 20)
{
...
}
C Programming Language 6 Halil Özmen
else
{
...
}
}
Dangling else:
if a then if b then s1 else s2
which can be understood in two ways.
Either as or as
if a then if a then
{ {
if b then if b then
{ {
s1 s1
} }
else }
{ else
s2 {
} s2
} }
"Dangling else" may occur when {...} is not used.
switch statement
switch ( variable )
{
case const:
statements...;
default:
statements...;
}
Exercises:
• Input two (or three) numbers, output them in ascending order.
• Input two integer numbers, output if 1st number is a multiple of the second.
Examples:
Add numbers from 41 to 100:
sum = 0; // sum must be initialized before the loop
for (k = 41; k <= 100; k++)
{
sum += k; // add number to the sum
}
printf ("Sum: %d\n", sum); // result must be processed after the loop
Count numbers divisible by 7 among the numbers from 200 to 400:
count = 0; // count must be initialized before the loop
for (k = 200; k <= 400; k++)
{
if ( (k % 7) == 0 )
{
while loops
Syntax:
while( expression )
{
statement(s)...;
}
Examples:
Count numbers divisible by 7 among the numbers from 200 to 400:
count = 0; // count must be initialized before the loop
k = 200;
while (k <= 400)
{
if ( k % 7 == 0 )
{
count++;
}
k++;
}
printf ("Count: %d\n", count);
Examples:
• Input y or Y (yes) or n or N (no).
• Input integer values between 0 and 8 (e.g. input selection of a menu).
Exercise:
• Input integer numbers until -999 is entered, output the number of even numbers.
C Programming Language 9 Halil Özmen
Algorithm templates: finding total, average, minimum, maximum.
Rules:
(1) Total (sum), count, max and min must be initialized before the loop starts.
(2) Average must be computed after the loop.
(3) Total, average, count, max and min must be used or output after the loop is
terminated.
Maximum:
printf ("Enter a number: ");
scanf ("%d", &num); // input first number
max = num; // max must be initialized before the
loop
while (num != SENTINEL_VALUE) // while number is not sentinel
value
{
if (num > max) // if number is greater than previous
max,
{ max = num; } // then this number is new max.
printf ("Enter a number: ");
scanf ("%d", &num); // input next number
}
printf ("Max: %d\n", max); // max must be used/output after the
loop
Usage of flag:
In some cases, the termination of a loop may depend on a condition that can be sensed in the
loop. In those cases, the loop condition may depend on a flag that is changed in an "if"
statement in the loop.
The following is a sample template for the usage of flag in loops:
flag = 1;
while (flag == 1 && some_other_condition)
{
statement(s)....
if (....)
{
C Programming Language 10 Halil Özmen
statement(s)....
flag = 0;
}
statement(s)....
}
Top-down design
To apply top-down design, the programmer starts with the broadest statement of the problem
solution and works down to more detailed subproblems.
Modular programming:
• understanding modularity:
instead of writing long code segments that performs many differnet tasks, it is much beter
to have shorter code segment where functions are called to perform specific tasks.
• parameter passing,
• returning values.
function call
Assume we have a function that computes the area of a circle given the radius:
function call
printf ("Menu\n");
printf ("1. Do this ....\n");
printf ("2. Do that ....\n");
printf ("3. Perform this ....\n");
printf ("0. Exit\n");
do
{
printf ("Select: );
scanf ("%d", &select);
} while(select < 0 || select > 3);
return (select);
} // end displaymenu
• By reference: this parameter passing technique is used if the value of the parameter will be
changed after the function call.
Example: scanf ("%d %d %lf", &num1, &num2, &x);
The values of num1, num2 and x are changed after the above function call is executed.
// Function protoype:
int is_prime (int num);
//==========================================================
// Gets a integer number as argument.
// Returns 1 if the number is prime, returns 0 otherwise.
int is_prime (int num)
{
int prime = 1;
int k;
if (num < 2)
{ return (0); }
for (k = 2; k <= sqrt(num); k++)
{
if (num % k == 0) // if num is divisible by k,
{
prime = 0; // then, num is not prime number.
break;
}
}
return (prime);
} // end is_prime
The variable k in the function is_prime is a completely different variable than the variable k in the
main function. They have different locations in memory.
Introduction to arrays:
An array is a collection of two or more adjacent memory cells, called array elements, that are
associated with a particular symbolic name.
In C, the array indices starts from 0 (zero). Therefore an array of 100 elements has indices from
0 to 99.
• Initialization during declaration: (values must be written between { and }, and separated by
comma.)
int v[10] = {12, 4, 52, 21, 40, -8, 10}; // last 3 are not initialized
index: 0 1 2 3 4 5 6 7 8 9
v: 12 4 52 21 40 -8 10
elements: v[0] v[1] v[2] v[3] v[4] v[5] v[6] v[7] v[8] v[9]
Exercises:
• Output the even numbers of an array containing n values. (Attention: numbers have to be even, not
indices.)
• Output the numbers that are divisible by 7 of an array containing n values.
• Output elements with indices 0, 4, 8, 12, ... (multiples of 4) of an array containing n values.
Exercises:
• Store the first 20 triangular numbers in an array. (A number is triangular if it is equal to
1+2+3+4+...+n.)
• Store the first 100 prime numbers in an array. Use a function is_prime that returns 1 if the number
in parameter is a prime number, returns 0 otherwise.
Example:
int main (void)
{
int ar[MAXSIZE];
int nar; // number of elements used in ar
. . .
sum = arrtotal (ar, nar);
. . .
doublearray(ar, nar);
. . .
} // end main
//=====================================
// This function returns the sum of numbers in the array.
// It does not change the array.
int arrtotal (int arr[], int numar)
{
int tot = 0, j;
for (j = 0; j < numar; j++)
{
tot += arr[j];
}
return (tot);
} // end arrtotal
//=====================================
// This function double every number in the array.
// It changes the array.
void doublearray (int arr[], int numar)
{
int j;
for (j = 0; j < numar; j++)
{
arr[j] = arr[j] + arr[j]; // or: arr[j] *= 2;
}
} // end doublearray
C Programming Language 18 Halil Özmen
Rule for arrays as function parameters:
If an array does not contain sentinel value (stopping value), then together with the array, the
number of used elements of the array must also be passed as parameter.
Exercises:
• Write a function that returns the maximum value in an array of numbers.
• Write a function that returns the average value of the numbers in an array.
• Write a function that returns the number of upper case letters in an array of characters.
• Write a function that returns the number of even numbers in an array.
• Write a function that changes numbers in an array, so that for odd numbered indices it stores the
squareroot of the number in that element, for even numbered indices it stores the square of the
number in that element.
Usage: both the first and the second indexes have to be specified to use the elements of a two
dimensional array.
mat[row][col] = a * 7; // here row and col are integer variables
if (names[n][j] != NULLCHAR) // the j'th char of the n'th string in names.
Examples:
// Fill an 8 by 8 matrix with 10.
for (r = 0; r < 8; r++)
{
for (c = 0; c < 8; c++)
{
ar[r][c] = 10;
}
}
Example:
int main()
{
int ar2[MAXROW][MAXCOL];
. . .
s = f1(ar2, nrow, ncol);
. . .
} // end main
//===========================================
// 1st dimension of the array parameter is not specified.
// Other dimensions are specified!
int f1 (int ar[][MAXCOL], int nrow, int ncol)
{
. . .
} // end f1
What is string? String is a data type to represent "textual data", like name or address.
Declaration:
char str1[11]; // Character string with at most 10 characters
Initialization:
char dept[] = "Computer Science"; // Valid declaration: size = 17
ATTENTION: 'Q' and "Q": 'Q' is a single character, and "Q" is a string. (see page 443)
String Assignment:
char string1[20]; /* use eg. MAXLEN instead of 20 */
string1 = "Test string"; /* ERROR: not a valid C statement */
strcpy(string1, "Test string");
strncpy(string1, "Test string", 20);
strncpy(string1, "Test string", 8);
Input/Output:
Character scanf("%c", &chr1);
Input chr1 = getchar();
chr1 = getc(stdin);
Output printf("%c", chr1);
putchar(chr1);
putc(chr1, stdout);
Word scanf("%s", string1); // ATTENTION: not &string1 but only string1
Input scanf("%s%s%d", last_name, first_name, &age); // separated by spaces
Output printf("%s", last_name);
printf("%s", str1); // Prints whole str1 even if it contains more than 1 words
Line gets(string1); // Gets a line from keyboard and stores in str1 (without \n)
Input fgets(str1, MAXLEN, stdin);
Output puts(string1);
printf("%s", string1);
C Programming Language 21 Halil Özmen
Input/Output String Format Qualifiers: "%ns" where n is the space allocated for the string.
Exercises:
1. Write a program that inputs a line of text, counts the number of blanks, and displays the number
of blanks.
2. Write a program that inputs a line of text, counts the number of blanks by using a function, and
displays the number of blanks. Perform this by modifying the above program.
3. Write a program that inputs a line of text and a symbol (character), counts the number of the
specific symbol by using a function, and outputs the count. Perform this by modifying the above
program.
4. Write a program that inputs a character and an unknown number of lines of text, counts the
number of the specific symbol in a line of text by using a function, and outputs the overall count.
Perform this by modifying the above program.
5. Write a program that inputs a line of text and two characters, replaces all the occurences of the
first character by the second character by using a function, and outputs the new string.
String Manipulation:
Data operations related with strings. With integers: add, subtract, multiply, divide.
With strings: ...
First, let's write some functions without using string manipulation library functions.
• Write a function which copies a string to another (char by char).
• Write a function that counts a character in a string. (a) ' ' Space (fixed); (b) A given char
(parameter).
• Write a function that checks if a string begins with another string. Then solve with "strstr" function.
Solutions of these three examples are on page 6.
String Length:
Number of characters in a string up to but not including null character '\0' at the end. (strlen())
String Comparison:
Comparison of characters: based on ASCII code of characters.
'A' < 'B' 'a' < 'b' '0' < '1' '0' < 'A' 'A' < 'a' 'Z' < 'a' '!' < '$'
String comparison is based on the character comparison in respective positions in the two
strings.
If two strings has identical characters for the length of shorter string, the longer string is greater
(after).
"ABCDEF" < "ABCDEG" "ZAA" < "a0" "Veli" < "ali" "Vali" < "Veli"
"VELI" < "Vali" "AX4520" < "AX94" "10" < "2" "Ali Veli" < "Ali"
Concatenation:
Concatenation is joining two strings (putting strings one after the other) to make a longer string.
Substring: Substring is a part (portion) of a string. Usually substring is defined by 3 elements: the
source string, the starting position and the length of substring.
strncpy(string2, string1+5, 8); /* Copies 8 chars starting from 5th char of
string1 */
strncpy(string2, &string1[5], 8); /* Copies 8 chars starting from 5th char of
string1 */
Substring Search: (See example function - long implementation without strstr.)
strptr = strstr(str1, str2);
if (strptr != NULL)
printf("Small string is in position %d in large string.\n", strptr-str1);
else
printf("Small string does not occur in large string.\n");
Insertion: This is the insertion of a string into a given position of another string. See the example
function.
Arrays of Strings:
#define NUM_PEOPLE 40
#define NAME_LEN 21
char names[NUM_PEOPLE][NAME_LEN];
char days[7][10] = {"Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"};
M o n d a y \0 ? ? ?
T u e s d a y \0 ? ?
W e d n e s d a y \0
T h u r s d a y \0 ?
F r i d a y \0 ? ? ?
S a t u r d a y \0 ?
S u n d a y \0 ? ? ?
Pointers to strings:
Frequently, there are needs to define pointers to strings in order to perform some string
manipulation functions.
Pointer is a data type which shows the address of data types.
In char name[20], when used alone "name" is a pointer to beginning of the char array which forms the
string.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
char line[MAX_LINE_LEN];
char *strptr;
. . .
gets(line);
for (strptr = line; *strptr != '\0'; strptr++)
{
....
}
Also, even more frequently, programmers need to make a string from number data types (int,
double, etc.). Eg: int day=2, month=10, year=2001, create a string as "02/10/2001".
The sscanf and sprintf can be used for string/number conversion purposes.
strcpy(line1, "1234");
sscanf(line1, "%d", &numint);
strcpy(line2, "624.234");
sscanf(line2, "%lf", &numdbl);
• Write a function that counts a character in a string. (a) ' ' Space (fixed); (b) A given char
(parameter).
Concatenation:
//len1 = strlen(last_name);
strcpy (name, last_name);
strcat (name, ", ");
strcat (name, first_name);
//name[len1+2+len2] = '\0'; /* NULL terminate the string */
Insertion: This is the insertion of a string into a given position of another string.
len1=strlen(str1);
if(pos <= 0 || pos > len1)
printf("Error, Position is out of bounds");
else
{
strcpy(temp1, &str1[pos]); /* Save 2nd part of str1 */
strcpy(&str1[pos], str2); /* Copy str2 to pos in str1 */
strcat(str1, temp1); /* Append the 2nd part of str1 */
}
} /* end insert_string */
Substring: Substring is a part (portion) of a string. Usually substring is defined by 3 elements: the
source string, the starting position and the length of substring.
strncpy(string2, string1+5, 8); // Copies 8 chars starting from 5th char of string1
strncpy(string2, &string1[5], 8); // Copies 8 chars starting from 5th char of string1
What is a structure in C?
What data is related with e.g. cars, students, courses, meals, planets, etc.? Think about various
data items. Each thing has data items like: name, size, weight, speed, color, address, location,
length, duration, etc.
"Structure in C" is a data structure which is a collection of various data elements that can be of
different data types.
Structure Declaration:
book_t book1, book2, new_book;
student_t student1, student2;
student2_t std1, std2;
cs_stu.gpa = 2.40;
strcpy(student1.name, "Ayhan");
student1.quiz1 = 64;
student1.overall = student1.quiz1 * 0.1 + student1.quiz2 * 0.1 +
student1.midterm * 0.3 + student1.final * 0.5;
student1.name[nlen] = NULLCHAR;
total = 0;
for(j = 0; j < 10; j++)
total += std1.grade[j]; // Example of array within structure
std1.overall = total / 10.0;
Example Programs:
1. Write a program that reads student information (id, name, birthyear) entered by the user into a
structure and display its contents. Write a function to read student info into a structure. Write a
function to display info in a given student structure.
/*------------------------------------------------------------------*/
/* Function that reads student information entered by the user and */
/* returns a structure. */
/*------------------------------------------------------------------*/
student_t read_student ()
{
student_t std;
char dummy[10];
return(std);
} /* end read_student */
Arrays of Structures:
student_t students[MAX_STUDENT];
#define MAXCHILD 10
typedef struct
{
person_t father; /* Father's information */
person_t mother; /* Mother's information */
int num_children; /* Number of children */
person_t child[MAXCHILD]; /* Children's information */
} family_t;
Pointers to Structures:
book_t text_book;
book_t ref_book;
book_t *book_ptr; /* pointer to a book structure */
book_ptr = &text_book; // assignment to book_ptr pointer
book_ptr
title author publisher pages price
/* Function */
double compute_overall(int q1, int q2, int midterm, int final)
{
return(q1 * 0.1 + q2 * 0.1 + midterm * 0.3 + final * 0.5);
}
/* Function */
void func1(student_t std)
{
. . .
printf("Final grade: %d\n", std.final);
. . .
} /* end func1 */
/* Function */
void func2(student_t *std_p)
{
. . .
scanf("%d", &(std_p->final) );
. . .
} /* end func2 */
Pointer Operators:
& operator: Address operator, gives the address of its operand.
&a address of variable a.
&aPtr address of aPtr.
* operator: It gives the content in an address.
*aPtr the content in the address aPtr.
aPtr = &a; // address of a is assigned to aPtr.
printf("%d\n", *aPtr); // prints content in address aPtr
NULL Pointer:
Sometimes a pointer may point to nothing, in this case is value is NULL. These are called NULL
pointer.
int k, *i_p;
double x, *d_p;
char c, *c_p;
char str[80] = "Foundation, Dune and The Lord Of The Rings";
Function that copies even numbers in array (a1) to another array (a2):
// copyEven: copies even numbers of a1 to a2.
int copyEven(int *a1, int n1, int *a2)
{ int copyEven(int *a1, int n1,
int n2 = 0; int *a2)
int j; {
for(j = 0; j < n1; j++) int n2 = 0;
{ int j;
if (*a1 % 2 == 0) for(j = 0; j < n1; j++)
{ {
*a2 = *a1; if (a1[j] % 2 == 0)
a2++; {
n2++; a2[n2] = a1[j];
} n2++;
a1++; }
} }
return (n2); return (n2);
} // end copyEven } // end copyEven
Function that copies alphabetic characters in a string (s1) to another string (s2):
// copyAlpha: copies alphabetic chars in s1 to s2.
void copyAlpha(char *s1, char *s2)
{
while(*s1 != NULLCHAR)
{
if(isalpha(*s1))
{
*s2 = *s1;
s2++;
}
s1++;
}
*s2 = NULLCHAR;
} // end copyAlpha
The C programming language provides several functions for memory allocation and management.
These functions can be found in the <stdlib.h> header file.
Function Description
void *malloc(int num); This function allocates an array of num bytes and leave
them uninitialized.
void *calloc(int num, int size); This function allocates an array of num elements each of
which is "size" bytes long.
void free(void *address); This function releases a block of memory block specified
by address.
void *realloc(void *address, int newsize); This function re-allocates memory extending it upto
newsize.
int main()
{
char name[STRSIZE] = "Amadeus Mozart";
char *sptr; // will point to dynamically allocated memory
Introduction
A linked list is a set of dynamically allocated nodes, arranged in such a way that each node contains
one value and one pointer. The pointer always points to the next member of the list. If the pointer is
NULL, then it is the last node in the list.
Linked lists have a few advantages over arrays:
1. Linked lists are dynamic. There is no need to define an initial size.
2. Items can be added to or removed from anywhere in the list.
However, linked lists also have a few disadvantages:
1. There is no "random" access - it is impossible to reach the nth item in the list without first iterating
over all items up until that item. This means we have to start from the beginning of the list and
count how many times we advance in the list until we get to the desired item.
2. Dynamic memory allocation and pointers are required, which complicates the code and
increases the risk of memory leaks and segment faults.
3. Linked lists have a much larger overhead over arrays, since linked list items are dynamically
allocated (which is less efficient in memory usage) and each item in the list also must store an
additional pointer.
What is a file?
A collection of data or information that has a name, called the filename. Almost all information
stored in the secondary storage of a computer must be in a file. There are many different types
of files: data files, text files, program files, directory files, and so on. Different types of files store
different types of information. For example, program files store programs, whereas text files
store text. The file extensions are important to distinguish among various file types: .txt -> text
files, .bin binary files, .c and .cpp program code files, .exe executable files etc.
End-of-File (EOF)
EOF is a special character that marks the end of the file. It is a defined constant in stdio.h.
Declaration:
FILE * fileptr; /* a pointer pointing to a file definition */
stdio.h contains a definition of type FILE which is used to store the information necessary for file
processing. For each file a separate FILE * must be declared.
Opening a file: In order to read from or to write into a file, the file must be opened (opening a file is
accessing to the file information and getting ready to make operations on that file). The fopen
function is used to open a file and returns the file pointer on success and NULL on error. (NULL
is a pointer pointing to nowhere; defined in standard libraries like stdio.h, stdlib.h
char filename[40]="c:\\cs101\\lab06\\names.txt";
infile = fopen(filename, "r");
outfile = fopen("newdata.txt","w");
if (infile == NULL)
{
printf("\n**** File does not exist! ****");
exit(EXIT_FAILURE);
}
exit is a standard function defined in stdlib.h and terminates a program. It causes all files to be
closed before terminating. A zero as a parameter to exit indicates a normal exit and a non-zero
indicates an error.
EXIT_SUCCESS and EXIT_FAILURE are constants defined in stdlib.h
Always close a file at the end of your program! Failure to close a file may cause trouble including
lost data, destroyed files and possible errors in your program!
fclose(infile);
C Programming Language 37 Halil Özmen
Functions related with files:
Function Description Parameters Returns on Returns on
Name success error
fopen opens a file string containing file name, FILE * NULL
string containing mode
fclose closes a file file pointer 0 EOF
fgetc reads a single character file pointer the character EOF
getc
fputc writes a single character character to write, file the character EOF
putc into an output file pointer
fgets reads a string from the string, number of string NULL
input file (keeps the characters, file pointer on end of file
newline, adds null ch)
fputs writes a string into the string, file pointer last character EOF
output file (does not place written
newline)
feof checks for end of file file pointer zero if end of file -
is reached,
non-zero if not
fscanf reads formatted data from a file pointer, format string, number of values EOF
text file variable list read on end of file
fprintf writes formatted data into a file pointer, format string,
text file variable list
Examples:
• Write a program that reads and display the contents of a text file.
• Write a program that reads characters from a text file and displays each character on a new line.
• Write a program that counts and displays the number of lines in a text file. Uses a function for
counting lines of a given file.
• Write a program that uses a function for counting the number of blanks in a text file and displays
the result.
Modes in Opening Binary Files:All the modes of text files are valid, only a 'b' is appended to the end
of the mode string. I.e.: "rb", "wb", "ab", "r+b", "w+b", "a+b".
sizeof is an operator that returns the size in bytes of a type or a variable or an expression.
sizeof(char) sizeof(int) sizeof(double) sizeof(string1) sizeof(numarr) sizeof(struct car_s)
Examples:
1. Write a program that creates a binary file named "int.bin" containing all integers between 1 and 50.
2. Write a function that reads integers form a binary file and use it to display contents of int.bin.
3. Read integers from a binary file and store the positive values in an array, negative values in another array.
4. Write a program that reads student information (id, name, birthyear) from text file (stu02.txt) into a structure
and display its contents. Name is enclosed between double-quotes in the input text file. Write a function to
read student info from a text file into a structure. Write a function to display info in a given student structure.
5. Write a program that reads student information (id, name, birthyear) from text file (stu02.txt) into a structure
and write into a binary file. Name is enclosed between double-quotes in the input text file. Write a function to
read student info from a text file into a structure.
6. Write a program that reads fast food information from text file into structure and writes into a binary file. Write
another program that reads this binary file and displays on screen.
Bitwise Operators:
Bitwise operators work on bits and perform bit by bit operations.
Assume: char A = 60, B = 13; Now in binary format they will be as follows:
A = 0011 1100 60
B = 0000 1101 13
---------------
A&B = 0000 1100 12 in decimal
A|B = 0011 1101 61 in decimal
A^B = 0011 0001 49 in decimal
~A = 1100 0011 -61.
if (n & 1) // if n is odd.
See: https://www.gnu.org/software/libc/manual/html_node/File-System-Interface.html
struct dirent
{
long d_ino; /* Always zero. */
unsigned short d_reclen; /* Always zero. */
unsigned short d_namlen; /* Length of name in d_name. */
char d_name[FILENAME_MAX]; /* File name. */
};
return 0;
}
See: https://www.gnu.org/software/libc/manual/html_node/Date-and-Time.html
• Time Basics: Concepts and definitions.
• Elapsed Time: Data types to represent elapsed times
• Processor and CPU Time: Time a program has spent executing.
• Calendar Time: Manipulation of “real” dates and times.
• Setting an Alarm: Sending a signal after a specified time.
• Sleeping: Waiting for a period of time.
https://www.gnu.org/software/libc/manual/html_node/Calendar-Time.html
https://www.gnu.org/software/libc/manual/html_node/Formatting-Calendar-Time.html
#include <stdio.h>
#include <time.h>
return 0;
}