SlideShare a Scribd company logo
1 of 30
1
 An Array is a collection of variables of the
same type that are referred to through a
common name.
 Declaration
type var_name[size]
e.g
2
int A[6];
double d[15];
After declaration, array contains some garbage
value.
Static initialization
Run time initialization
3
int month_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int i;
int A[6];
for(i = 0; i < 6; i++)
A[i] = 6 - i;
int A[6];
6 elements of 4 bytes each,
total size = 6 x 4 bytes = 24 bytes
Read an element
Write to an element
{program: array_average.c}
4
A[0] A[1] A[2] A[3] A[4] A[5]
0x1000 0x1004 0x1008 0x1012 0x1016 0x1020
6 5 4 3 2 1
int tmp = A[2];
A[3] = 5;
 No “Strings” keyword
 A string is an array of characters.
OR
5
char string[] = “hello world”;
char *string = “hello world”;
• Compiler has to know where the string ends
• ‘0’ denotes the end of string
{program: hello.c}
Some more characters (do $man ascii):
‘n’ = new line, ‘t’ = horizontal tab, ‘v’ =
vertical tab, ‘r’ = carriage return
‘A’ = 0x41, ‘a’ = 0x61, ‘0’ = 0x00
6
char string[] = “hello world”;
printf(“%s”, string);
 aggregate in that they hold multiple data items at
one time
 named members hold data items of various types
 like the notion of class/field in C or C++
– but without the data hiding features
 scalar in that C treats each structure as a unit
 as opposed to the “array” approach: a pointer to a
collection of members in memory
 entire structures (not just pointers to structures) may be
passed as function arguments, assigned to variables,
etc.
 Interestingly, they cannot be compared using ==
(rationale: too inefficient)
7
 Combined variable and type declaration
struct tag {member-list} variable-list;
 Any one of the three portions can be omitted
struct {int a, b; char *p;} x, y; /* omit tag */
 variables x, y declared with members as described:
int members a, b and char pointer p.
 x and y have same type, but differ from all others –
even if there is another declaration:
struct {int a, b; char *p;} z;
/* z has different type from x, y */
8
struct S {int a, b; char *p;}; /* omit variables */
 No variables are declared, but there is now a type
struct S that can be referred to later
struct S z; /* omit members */
 Given an earlier declaration of struct S, this declares a
variable of that type
typedef struct {int a, b; char *p;} S;
/* omit both tag and variables */
 This creates a simple type name S
(more convenient than struct S)
9
 Direct access operator s.m
 subscript and dot operators have same precedence and
associate left-to-right, so we don’t need parentheses for
sam.pets[0].species
 Indirect access s->m: equivalent to (*s).m
 Dereference a pointer to a structure, then return a
member of that structure
 Dot operator has higher precedence than indirection
operator , so parentheses are needed in (*s).m
(*fido.owner).name or fido.owner->name
10
. evaluated first: access owner member
* evaluated next: dereference pointer to
HUMAN
. and -> have equal precedence
and associate left-to-right
 Portability is an issue:
 Do any bit field sizes exceed the machine’s int size?
 Is there any pointer manipulation in your code that
assumes a particular layout?
 Bit fields are “syntactic sugar” for more complex
shifting/masking
 e.g. to get font value, mask off the ch and size bits,
then shift right by 19
 This is what actually happens in the object code –
bit fields just make it look simpler at the source level
11
 Structures are scalars, so they can be returned and
passed as arguments – just like ints, chars
struct BIG changestruct(struct BIG s);
 Call by value: temporary copy of structure is created
 Caution: passing large structures is inefficient
– involves a lot of copying
 avoid by passing a pointer to the structure instead:
void changestruct(struct BIG *s);
 What if the struct argument is read-only?
 Safe approach: use const
void changestruct(struct BIG const *s);
12
 Like structures, but every member occupies the
same region of memory!
 Structures: members are “and”ed together: “name and
species and owner”
 Unions: members are “xor”ed together
union VALUE {
float f;
int i;
char *s;
};
/* either a float xor an int xor a string */
13
 Up to programmer to determine how to interpret a
union (i.e. which member to access)
 Often used in conjunction with a “type” variable
that indicates how to interpret the union value
enum TYPE { INT, FLOAT, STRING };
struct VARIABLE {
enum TYPE type;
union VALUE value;
};
14
Access type to determine
how to interpret value
 Storage
 size of union is the size of its largest member
 avoid unions with widely varying member sizes;
for the larger data types, consider using pointers instead
 Initialization
 Union may only be initialized to a value appropriate for
the type of its first member
15
 File – place on disc where group of related
data is stored
 E.g. your C programs, executables
 High-level programming languages support
file operations
 Naming
 Opening
 Reading
 Writing
 Closing
 fp
 contains all information about file
 Communication link between system and program
 Mode can be
 r open file for reading only
 w open file for writing only
 a open file for appending (adding) data
FILE *fp; /*variable fp is pointer to type FILE*/
fp = fopen(“filename”, “mode”);
/*opens file with name filename , assigns identifier to fp */
 Writing mode
 if file already exists then contents are deleted,
 else new file with specified name created
 Appending mode
 if file already exists then file opened with contents safe
 else new file created
 Reading mode
 if file already exists then opened with contents safe
 else error occurs.
FILE *p1, *p2;
p1 = fopen(“data”,”r”);
p2= fopen(“results”, w”);
 r+ open to beginning for both
reading/writing
 w+ same as w except both for reading and
writing
 a+ same as ‘a’ except both for reading and
writing
 File must be closed as soon as all operations on it completed
 Ensures
 All outstanding information associated with file flushed out from
buffers
 All links to file broken
 Accidental misuse of file prevented
 If want to change mode of file, then first close and open
again
Syntax: fclose(file_pointer);
Example:
FILE *p1, *p2;
p1 = fopen(“INPUT.txt”, “r”);
p2 =fopen(“OUTPUT.txt”, “w”);
……..
……..
fclose(p1);
fclose(p2);
 C provides several different functions for
reading/writing
 getc() – read a character
 putc() – write a character
 fprintf() – write set of data values
 fscanf() – read set of data values
 getw() – read integer
 putw() – write integer
 handle one character at a time like getchar() and
putchar()
 syntax: putc(c,fp1);
 c : a character variable
 fp1 : pointer to file opened with mode w
 syntax: c = getc(fp2);
 c : a character variable
 fp2 : pointer to file opened with mode r
 file pointer moves by one character position after every
getc() and putc()
 getc() returns end-of-file marker EOF when file end
reached
#include <stdio.h>
main()
{ FILE *fp1;
char c;
f1= fopen(“INPUT”, “w”); /* open file for writing */
while((c=getchar()) != EOF) /*get char from keyboard
until CTL-Z*/
putc(c,f1); /*write a
character to INPUT */
fclose(f1); /* close INPUT
*/
f1=fopen(“INPUT”, “r”); /* reopen file */
while((c=getc(f1))!=EOF) /*read character from file INPUT*/
printf(“%c”, c); /* print character to
screen */
fclose(f1);
} /*end main */
• similar to scanf() and printf()
• in addition provide file-pointer
• given the following
– file-pointer f1 (points to file opened in write mode)
– file-pointer f2 (points to file opened in read mode)
– integer variable i
– float variable f
• Example:
fprintf(f1, “%d %fn”, i, f);
fprintf(stdout, “%f n”, f); /*note: stdout refers to
screen */
fscanf(f2, “%d %f”, &i, &f);
• fscanf returns EOF when end-of-file reached
 handle one integer at a time
 syntax: putw(i,fp1);
 i : an integer variable
 fp1 : pointer to file ipened with mode w
 syntax: i = getw(fp2);
 i : an integer variable
 fp2 : pointer to file opened with mode r
 file pointer moves by one integer position, data
stored in binary format native to local system
 getw() returns end-of-file marker EOF when file end
reached
 Typical errors that occur
 trying to read beyond end-of-file
 trying to use a file that has not been opened
 perform operation on file not permitted by
‘fopen’ mode
 open file with invalid filename
 write to write-protected file
 given file-pointer, check if EOF reached, errors
while handling file, problems opening file etc.
 check if EOF reached: feof()
 feof() takes file-pointer as input, returns nonzero if
all data read and zero otherwise
if(feof(fp))
printf(“End of datan”);
 ferror() takes file-pointer as input, returns nonzero
integer if error detected else returns zero
if(ferror(fp) !=0)
printf(“An error has occurredn”);
 if file cannot be opened then fopen returns a
NULL pointer
 Good practice to check if pointer is NULL
before proceeding
fp = fopen(“input.dat”, “r”);
if (fp == NULL)
printf(“File could not be opened n ”);
 how to jump to a given position (byte number) in a
file without reading all the previous data?
 fseek (file-pointer, offset, position);
 position: 0 (beginning), 1 (current), 2 (end)
 offset: number of locations to move from position
Example: fseek(fp,-m, 1); /* move back by m bytes from
current
position */
fseek(fp,m,0); /* move to (m+1)th byte in file
*/
fseek(fp, -10, 2); /* what is this? */
 ftell(fp) returns current byte position in file
 rewind(fp) resets position to start of file
 can give input to C program from command line
E.g. > prog.c 10
name1 name2 ….
 how to use these arguments?
main ( int argc, char *argv[] )
 argc – gives a count of number of arguments
(including program name)
 char *argv[] defines an array of pointers to
character (or array of strings)
 argv[0] – program name
 argv[1] to argv[argc -1] give the other arguments
as strings

More Related Content

What's hot

C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYC UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
Rajeshkumar Reddy
 
Read write program
Read write programRead write program
Read write program
AMI AMITO
 
Files let you store data on secondary storage such as a hard disk so that you...
Files let you store data on secondary storage such as a hard disk so that you...Files let you store data on secondary storage such as a hard disk so that you...
Files let you store data on secondary storage such as a hard disk so that you...
Bern Jamie
 
Unit5 (2)
Unit5 (2)Unit5 (2)
Unit5 (2)
mrecedu
 
file handling c++
file handling c++file handling c++
file handling c++
Guddu Spy
 

What's hot (19)

C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYC UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
 
File Management in C
File Management in CFile Management in C
File Management in C
 
Unit 5 dwqb ans
Unit 5 dwqb ansUnit 5 dwqb ans
Unit 5 dwqb ans
 
Read write program
Read write programRead write program
Read write program
 
Files in C
Files in CFiles in C
Files in C
 
File handling in c
File handling in cFile handling in c
File handling in c
 
File handling-c
File handling-cFile handling-c
File handling-c
 
Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'
 
5 Structure & File.pptx
5 Structure & File.pptx5 Structure & File.pptx
5 Structure & File.pptx
 
File Management
File ManagementFile Management
File Management
 
Satz1
Satz1Satz1
Satz1
 
Files let you store data on secondary storage such as a hard disk so that you...
Files let you store data on secondary storage such as a hard disk so that you...Files let you store data on secondary storage such as a hard disk so that you...
Files let you store data on secondary storage such as a hard disk so that you...
 
Clone detection in Python
Clone detection in PythonClone detection in Python
Clone detection in Python
 
Unsupervised Machine Learning for clone detection
Unsupervised Machine Learning for clone detectionUnsupervised Machine Learning for clone detection
Unsupervised Machine Learning for clone detection
 
Programming in C
Programming in CProgramming in C
Programming in C
 
C Language Unit-5
C Language Unit-5C Language Unit-5
C Language Unit-5
 
Clonedigger-Python
Clonedigger-PythonClonedigger-Python
Clonedigger-Python
 
Unit5 (2)
Unit5 (2)Unit5 (2)
Unit5 (2)
 
file handling c++
file handling c++file handling c++
file handling c++
 

Similar to Programming in C

Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
patcha535
 

Similar to Programming in C (20)

Unit5 C
Unit5 C Unit5 C
Unit5 C
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
File Handling in c.ppt
File Handling in c.pptFile Handling in c.ppt
File Handling in c.ppt
 
Introduction to Data Structure : Pointer
Introduction to Data Structure : PointerIntroduction to Data Structure : Pointer
Introduction to Data Structure : Pointer
 
File in C language
File in C languageFile in C language
File in C language
 
Unit5
Unit5Unit5
Unit5
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
File handling in C
File handling in CFile handling in C
File handling in C
 
Files_in_C.ppt
Files_in_C.pptFiles_in_C.ppt
Files_in_C.ppt
 
Bt0067 c programming and data structures2
Bt0067 c programming and data structures2Bt0067 c programming and data structures2
Bt0067 c programming and data structures2
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
 
File management
File managementFile management
File management
 
slides3_077.ppt
slides3_077.pptslides3_077.ppt
slides3_077.ppt
 
Handout#01
Handout#01Handout#01
Handout#01
 
Unit v
Unit vUnit v
Unit v
 
File management and handling by prabhakar
File management and handling by prabhakarFile management and handling by prabhakar
File management and handling by prabhakar
 
file.ppt
file.pptfile.ppt
file.ppt
 
File handling in c
File handling in cFile handling in c
File handling in c
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Recently uploaded (20)

On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 

Programming in C

  • 1. 1
  • 2.  An Array is a collection of variables of the same type that are referred to through a common name.  Declaration type var_name[size] e.g 2 int A[6]; double d[15];
  • 3. After declaration, array contains some garbage value. Static initialization Run time initialization 3 int month_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int i; int A[6]; for(i = 0; i < 6; i++) A[i] = 6 - i;
  • 4. int A[6]; 6 elements of 4 bytes each, total size = 6 x 4 bytes = 24 bytes Read an element Write to an element {program: array_average.c} 4 A[0] A[1] A[2] A[3] A[4] A[5] 0x1000 0x1004 0x1008 0x1012 0x1016 0x1020 6 5 4 3 2 1 int tmp = A[2]; A[3] = 5;
  • 5.  No “Strings” keyword  A string is an array of characters. OR 5 char string[] = “hello world”; char *string = “hello world”;
  • 6. • Compiler has to know where the string ends • ‘0’ denotes the end of string {program: hello.c} Some more characters (do $man ascii): ‘n’ = new line, ‘t’ = horizontal tab, ‘v’ = vertical tab, ‘r’ = carriage return ‘A’ = 0x41, ‘a’ = 0x61, ‘0’ = 0x00 6 char string[] = “hello world”; printf(“%s”, string);
  • 7.  aggregate in that they hold multiple data items at one time  named members hold data items of various types  like the notion of class/field in C or C++ – but without the data hiding features  scalar in that C treats each structure as a unit  as opposed to the “array” approach: a pointer to a collection of members in memory  entire structures (not just pointers to structures) may be passed as function arguments, assigned to variables, etc.  Interestingly, they cannot be compared using == (rationale: too inefficient) 7
  • 8.  Combined variable and type declaration struct tag {member-list} variable-list;  Any one of the three portions can be omitted struct {int a, b; char *p;} x, y; /* omit tag */  variables x, y declared with members as described: int members a, b and char pointer p.  x and y have same type, but differ from all others – even if there is another declaration: struct {int a, b; char *p;} z; /* z has different type from x, y */ 8
  • 9. struct S {int a, b; char *p;}; /* omit variables */  No variables are declared, but there is now a type struct S that can be referred to later struct S z; /* omit members */  Given an earlier declaration of struct S, this declares a variable of that type typedef struct {int a, b; char *p;} S; /* omit both tag and variables */  This creates a simple type name S (more convenient than struct S) 9
  • 10.  Direct access operator s.m  subscript and dot operators have same precedence and associate left-to-right, so we don’t need parentheses for sam.pets[0].species  Indirect access s->m: equivalent to (*s).m  Dereference a pointer to a structure, then return a member of that structure  Dot operator has higher precedence than indirection operator , so parentheses are needed in (*s).m (*fido.owner).name or fido.owner->name 10 . evaluated first: access owner member * evaluated next: dereference pointer to HUMAN . and -> have equal precedence and associate left-to-right
  • 11.  Portability is an issue:  Do any bit field sizes exceed the machine’s int size?  Is there any pointer manipulation in your code that assumes a particular layout?  Bit fields are “syntactic sugar” for more complex shifting/masking  e.g. to get font value, mask off the ch and size bits, then shift right by 19  This is what actually happens in the object code – bit fields just make it look simpler at the source level 11
  • 12.  Structures are scalars, so they can be returned and passed as arguments – just like ints, chars struct BIG changestruct(struct BIG s);  Call by value: temporary copy of structure is created  Caution: passing large structures is inefficient – involves a lot of copying  avoid by passing a pointer to the structure instead: void changestruct(struct BIG *s);  What if the struct argument is read-only?  Safe approach: use const void changestruct(struct BIG const *s); 12
  • 13.  Like structures, but every member occupies the same region of memory!  Structures: members are “and”ed together: “name and species and owner”  Unions: members are “xor”ed together union VALUE { float f; int i; char *s; }; /* either a float xor an int xor a string */ 13
  • 14.  Up to programmer to determine how to interpret a union (i.e. which member to access)  Often used in conjunction with a “type” variable that indicates how to interpret the union value enum TYPE { INT, FLOAT, STRING }; struct VARIABLE { enum TYPE type; union VALUE value; }; 14 Access type to determine how to interpret value
  • 15.  Storage  size of union is the size of its largest member  avoid unions with widely varying member sizes; for the larger data types, consider using pointers instead  Initialization  Union may only be initialized to a value appropriate for the type of its first member 15
  • 16.  File – place on disc where group of related data is stored  E.g. your C programs, executables  High-level programming languages support file operations  Naming  Opening  Reading  Writing  Closing
  • 17.  fp  contains all information about file  Communication link between system and program  Mode can be  r open file for reading only  w open file for writing only  a open file for appending (adding) data FILE *fp; /*variable fp is pointer to type FILE*/ fp = fopen(“filename”, “mode”); /*opens file with name filename , assigns identifier to fp */
  • 18.  Writing mode  if file already exists then contents are deleted,  else new file with specified name created  Appending mode  if file already exists then file opened with contents safe  else new file created  Reading mode  if file already exists then opened with contents safe  else error occurs. FILE *p1, *p2; p1 = fopen(“data”,”r”); p2= fopen(“results”, w”);
  • 19.  r+ open to beginning for both reading/writing  w+ same as w except both for reading and writing  a+ same as ‘a’ except both for reading and writing
  • 20.  File must be closed as soon as all operations on it completed  Ensures  All outstanding information associated with file flushed out from buffers  All links to file broken  Accidental misuse of file prevented  If want to change mode of file, then first close and open again Syntax: fclose(file_pointer); Example: FILE *p1, *p2; p1 = fopen(“INPUT.txt”, “r”); p2 =fopen(“OUTPUT.txt”, “w”); …….. …….. fclose(p1); fclose(p2);
  • 21.  C provides several different functions for reading/writing  getc() – read a character  putc() – write a character  fprintf() – write set of data values  fscanf() – read set of data values  getw() – read integer  putw() – write integer
  • 22.  handle one character at a time like getchar() and putchar()  syntax: putc(c,fp1);  c : a character variable  fp1 : pointer to file opened with mode w  syntax: c = getc(fp2);  c : a character variable  fp2 : pointer to file opened with mode r  file pointer moves by one character position after every getc() and putc()  getc() returns end-of-file marker EOF when file end reached
  • 23. #include <stdio.h> main() { FILE *fp1; char c; f1= fopen(“INPUT”, “w”); /* open file for writing */ while((c=getchar()) != EOF) /*get char from keyboard until CTL-Z*/ putc(c,f1); /*write a character to INPUT */ fclose(f1); /* close INPUT */ f1=fopen(“INPUT”, “r”); /* reopen file */ while((c=getc(f1))!=EOF) /*read character from file INPUT*/ printf(“%c”, c); /* print character to screen */ fclose(f1); } /*end main */
  • 24. • similar to scanf() and printf() • in addition provide file-pointer • given the following – file-pointer f1 (points to file opened in write mode) – file-pointer f2 (points to file opened in read mode) – integer variable i – float variable f • Example: fprintf(f1, “%d %fn”, i, f); fprintf(stdout, “%f n”, f); /*note: stdout refers to screen */ fscanf(f2, “%d %f”, &i, &f); • fscanf returns EOF when end-of-file reached
  • 25.  handle one integer at a time  syntax: putw(i,fp1);  i : an integer variable  fp1 : pointer to file ipened with mode w  syntax: i = getw(fp2);  i : an integer variable  fp2 : pointer to file opened with mode r  file pointer moves by one integer position, data stored in binary format native to local system  getw() returns end-of-file marker EOF when file end reached
  • 26.  Typical errors that occur  trying to read beyond end-of-file  trying to use a file that has not been opened  perform operation on file not permitted by ‘fopen’ mode  open file with invalid filename  write to write-protected file
  • 27.  given file-pointer, check if EOF reached, errors while handling file, problems opening file etc.  check if EOF reached: feof()  feof() takes file-pointer as input, returns nonzero if all data read and zero otherwise if(feof(fp)) printf(“End of datan”);  ferror() takes file-pointer as input, returns nonzero integer if error detected else returns zero if(ferror(fp) !=0) printf(“An error has occurredn”);
  • 28.  if file cannot be opened then fopen returns a NULL pointer  Good practice to check if pointer is NULL before proceeding fp = fopen(“input.dat”, “r”); if (fp == NULL) printf(“File could not be opened n ”);
  • 29.  how to jump to a given position (byte number) in a file without reading all the previous data?  fseek (file-pointer, offset, position);  position: 0 (beginning), 1 (current), 2 (end)  offset: number of locations to move from position Example: fseek(fp,-m, 1); /* move back by m bytes from current position */ fseek(fp,m,0); /* move to (m+1)th byte in file */ fseek(fp, -10, 2); /* what is this? */  ftell(fp) returns current byte position in file  rewind(fp) resets position to start of file
  • 30.  can give input to C program from command line E.g. > prog.c 10 name1 name2 ….  how to use these arguments? main ( int argc, char *argv[] )  argc – gives a count of number of arguments (including program name)  char *argv[] defines an array of pointers to character (or array of strings)  argv[0] – program name  argv[1] to argv[argc -1] give the other arguments as strings