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
 

More from sujathavvv (15)

Vector calculus
Vector calculusVector calculus
Vector calculus
 
Complex analysis
Complex analysisComplex analysis
Complex analysis
 
Z transforms
Z transformsZ transforms
Z transforms
 
Formatted Console I/O Operations in C++
Formatted Console I/O Operations in C++Formatted Console I/O Operations in C++
Formatted Console I/O Operations in C++
 
Programming in c++ ppt
Programming in c++ pptProgramming in c++ ppt
Programming in c++ ppt
 
Vector calculus
Vector calculusVector calculus
Vector calculus
 
Programming in c++
Programming in c++Programming in c++
Programming in c++
 
Complex analysis
Complex analysisComplex analysis
Complex analysis
 
Trigonometry & vector calculus
Trigonometry & vector calculusTrigonometry & vector calculus
Trigonometry & vector calculus
 
Complex analysis
Complex analysisComplex analysis
Complex analysis
 
Differential equation and Laplace Transform
Differential equation and Laplace TransformDifferential equation and Laplace Transform
Differential equation and Laplace Transform
 
Differential equation and Laplace transform
Differential equation and Laplace transformDifferential equation and Laplace transform
Differential equation and Laplace transform
 
Sequences and Series
Sequences and SeriesSequences and Series
Sequences and Series
 
Sequences and Series
Sequences and SeriesSequences and Series
Sequences and Series
 
Programming in c
Programming in cProgramming in c
Programming in c
 

Recently uploaded

Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
EADTU
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Economic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food AdditivesEconomic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food Additives
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of Play
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Introduction to TechSoup’s Digital Marketing Services and Use Cases
Introduction to TechSoup’s Digital Marketing  Services and Use CasesIntroduction to TechSoup’s Digital Marketing  Services and Use Cases
Introduction to TechSoup’s Digital Marketing Services and Use Cases
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
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
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
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
 
Our Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdfOur Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdf
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 

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