0% found this document useful (0 votes)
116 views52 pages

01-Structures, Unions, Enumerations, File Processing

The document discusses C data structures including structures, unions, enumerations, and file processing. It provides examples of defining and using structures to store related data, accessing structure members, passing structures to functions, and arrays of structures. It also covers unions, enumerations, opening, reading and writing files, and the end-of-file marker. The examples demonstrate storing student records in a structure and reading/writing them to a file.

Uploaded by

hannah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
116 views52 pages

01-Structures, Unions, Enumerations, File Processing

The document discusses C data structures including structures, unions, enumerations, and file processing. It provides examples of defining and using structures to store related data, accessing structure members, passing structures to functions, and arrays of structures. It also covers unions, enumerations, opening, reading and writing files, and the end-of-file marker. The examples demonstrate storing student records in a structure and reading/writing them to a file.

Uploaded by

hannah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

ALGOTIHMS

&
DATA STRUCTURES
01 ‒ Structures, Unions, Enumerations, & File Processing

Dennis Gunawan
Farica Perdana Putri
STRUCTURES
• Collections of related variables under one name

• Structures may contain variables of many different data types

• Example: a student has name, major, and GPA


STRUCTURE DEFINITIONS
• Syntax
struct [structure_tag]
{
data_type member_var_name [,member_var_name,...];
[data_type member_var_name [,member_var_name,...];]
} [structure_var_name];

struct structure_tag
• Defining variables of structure types
struct struct_tag struct_var_name [,struct_var_name,...];
STRUCTURE DEFINITIONS
struct student
{
struct student char name[50];
{ char major[35];
char name[50]; float gpa;
char major[35]; }anthony;
float gpa;
}; struct
{
struct student anthony; char name[50];
char major[35];
float gpa;
}anthony;
INITIALIZING STRUCTURES
• Syntax
struct struct_tag struct_var_name = {value1, value2, ..., valuen};

• Example

struct student anthony = {“Anthony”, “Informatics”, 3.99};


ACCESSING STRUCTURE MEMBERS
• Structure member operator = dot operator ( . )
• The structure member operator accesses a structure member via the structure
variable name

printf(“%s\n”, anthony.name);
printf(“%s\n”, anthony.major);
printf(“%f\n”, anthony.gpa);
ACCESSING STRUCTURE MEMBERS
ACCESSING STRUCTURE MEMBERS
• Structure pointer operator = arrow operator ( -> )
• Consists of a minus ( - ) sign and a greater than ( > ) sign with no intervening
spaces
• The structure pointer operator accesses a structure member via a pointer to the
structure
struct student *anthonyPtr;

?
(*anthonyPtr).name anthonyPtr = &anthony;
(*anthonyPtr).major
(*anthonyPtr).gpa printf(“%s\n”,anthonyPtr->name);
printf(“%s\n”,anthonyPtr->major);
printf(“%f\n”,anthonyPtr->gpa);
ACCESSING STRUCTURE MEMBERS
ACCESSING STRUCTURE MEMBERS
GLOBAL SCOPE vs LOCAL SCOPE
GLOBAL SCOPE vs LOCAL SCOPE
USING STRUCTURES WITH FUNCTIONS
• Structures may be passed to functions by passing individual structure members,
by passing an entire structure, or by passing a pointer to a structure

• When structures or individual structure members are passed to a function, they


are passed by value

• To pass a structure by reference (pointer), pass the address of the structure


variable
USING STRUCTURES WITH FUNCTIONS
USING STRUCTURES WITH FUNCTIONS
USING STRUCTURES WITH FUNCTIONS
ARRAY OF STRUCTURES
ARRAY OF STRUCTURES
NESTED STRUCTURES
TYPEDEF
• The keyword typedef provides a mechanism for creating synonyms (or aliases)
for previously defined data types

• Names for structure types are often defined with typedef to create shorter type
names

• C programmers often use typedef to define a structure type, so a structure tag


is not required
TYPEDEF
UNIONS
• A derived data type with members that share the same storage space

• A union shares the space instead of wasting storage on variables that are not
being used

• The number of bytes used to store a union must be at least enough to hold the
largest member

• In most cases, unions contain two or more data types


UNIONS
• Syntax
union [union_tag]
{
data_type member_var_name [,member_var_name,...];
[data_type member_var_name [,member_var_name,...];]
} [union_var_name];

• Defining variables of union types


union union_tag union_var_name;
UNIONS

union d
member 1 number
member 2 c[1] c[0]
bit 8 7 6 5 4 3 2 1 8 7 6 5 4 3 2 1
value 0 1 0 0 0 1 0 0 0 1 0 0 0 1 1 1
ENUMERATIONS
• A set of integer enumeration constants represented by identifiers

• Values in an enumeration start with 0, unless specified otherwise, and


incremented by 1
ENUMERATIONS
• Syntax
enum [enum_tag]
{
member1, member2, ..., membern
} [enum_var_name];

• Defining variables of enumeration types


enum enum_tag enum_var_name;
ENUMERATIONS
• Examples
enum months
{
JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
};

enum months
{
JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
};
ENUMERATIONS
FILE PROCESSING
• Storage of data in variables and arrays is temporary
• Such data is lost when a program terminates

• Files are used for permanent retention of data

• Computers store files on secondary storage devices, especially disk storage


devices
DATA HIERARCHY
Brandon Informatics 3.99
Devin Informatics 3.62 File
Shendy Informatics 3.75

Brandon Informatics 3.99 Record

Brandon Field

01000010 Byte

1 Bit
FILES AND STREAMS
• C views each file simply as a sequential stream of bytes

• Each file ends with an end-of-file marker

• When a file is opened, a stream is associated with the file

• Streams provide communication channels between files and programs


FILES AND STREAMS
• C s view of a file of n bytes

0 1 2 3 4 5 6 7 8 9 … n-1
… end-of-file marker
OPENING A FILE
• Syntax
FILE *fopen(const char *name, const char *mode);

• The fopen() function opens the file with the specified name
• The second argument is a character string that specifies the requested
access mode
• fopen() returns the FILE pointer for you to use in subsequent input or
output operations on the file, or a null pointer if the function fails to open
the file with the requested access mode
• Example
FILE *fp = fopen(“data.txt”, “r”);
OPENING A FILE
• File Access Modes

Mode String Access Mode Notes


r Read
The file must already exist
r+ Read and write
w Write If the file does not exist, fopen() creates it
If it does exist, fopen() erases its contents on
w+ Write and read opening
a Append
If the file does not exist, fopen() creates it
a+ Append and Writing is done at the end of the file
read
READING DATA FROM A FILE
data.txt
Brandon Tanujaya#Informatics#3.99
• Syntax
char *fgets(char *buffer, int n, FILE *fp);

• The fgets() function reads a sequence of up to n-1 characters from the file
referenced by the FILE pointer argument, and writes it to the buffer indicated by
the char pointer argument, appending the string terminator character \0

• Example
char data[70]; If a newline character ( \n ) is read, reading
FILE *fp = fopen(“data.txt”, “r”); stops and the string written to the buffer is
fgets(data, 70, fp); terminated after the newline character
READING DATA FROM A FILE
data.txt
Brandon Tanujaya#Informatics#3.99
• Syntax
int fscanf(FILE *fp, const char *format, ...);

• The fscanf() function is like scanf(), except that it reads input from the file
referenced by first argument, fp, rather than from stdin

• Example
float gpa;
char name[50], major[35];
FILE *fp = fopen(“data.txt”, “r”);
fscanf(fp, “%[^#]#%[^#]#%f”, name, major, &gpa);
WRITING DATA TO A FILE
data.txt
Oktavius Wiguna#Informatics#3.97
• Syntax
int fputs(const char *string, FILE *fp);

• The fputs() function writes a string to the file specified by the FILE pointer
argument

• Example
char data[70] = “Oktavius Wiguna#Informatics#3.97”;
FILE *fp = fopen(“data.txt”, “w”);
fputs(data, fp);
END-OF-FILE MARKER

• Syntax
int feof(FILE *fp);

• The feof() function tests whether the file position indicator of a given file is at the
end of the file
END-OF-FILE MARKER
data.txt
struct student
{
Brandon Tanujaya#Informatics#3.99
char name[50]; Oktavius Wiguna#Informatics#3.97
char major[35]; Shendy Harlim#Informatics#3.75
float gpa;
};

int i = 0;
struct student s[3];
FILE *fp = fopen(“data.txt”, “r”);
while(!feof(fp))
{
fscanf(fp, “%[^#]#%[^#]#%f\n”, s[i].name, s[i].major, &s[i].gpa);
i++;
}
CLOSING A FILE
• Syntax
int fclose(FILE *fp);

• The fclose() function closes the file associated with a given FILE pointer,
and releases the memory occupied by its I/O buffer

• Example
fclose(fp);
EXAMPLES

data.txt

output.txt
EXAMPLES

data.txt

output.txt
PRACTICE
PRACTICE 0
• Define a structure type named long_lat that would be appropriate for storing
longitude or latitude values. Include components named degrees (an integer),
minutes (an integer), and direction (one of the characters N , S , E , or W ).
PRACTICE 0
• The following are a structure type to represent a geographic location and a
variable of this hierarchical structure type

typedef struct
{
char place[20];
long_lat longitude, latitude;
} location_t;

location_t resort;
PRACTICE 0
• Given that the values shown have been stored in resort
.place Hawaii\0
.longitude 158 0 W
.latitude 21 30 N

• Complete the following table


Reference Data Type of Reference Value
resort.latitude long_lat 21 30 N
resort.place … …
resort.longitude.directio
… …
n
… … 30
resort.place[3] … …
PRACTICE 1
• Complete the following program

#include <stdio.h> int main()


{
struct product struct product p;
{
char product_id[6];
char product_name[31];
?
float product_price; return 0;
}; }
PRACTICE 1
• The screen dialogue should appear as follows:

ID : P0001
Name : Bluetooth Mouse
Price : 550000

Product ID : P0001
Product Name : Bluetooth Mouse
Product Price : Rp550000.00
PRACTICE 2
• Write two functions: inputProduct and showProduct

#include <stdio.h> int main()


{
struct product struct product p;
{
char product_id[6]; inputProduct(&p);
char product_name[31]; showProduct(p);
float product_price;
}; return 0;
}
PRACTICE 2
• The screen dialogue should appear as follows:

ID : P0001
Name : Bluetooth Mouse
Price : 550000

Product ID : P0001
Product Name : Bluetooth Mouse
Product Price : Rp550000.00
PRACTICE 3 bill.txt
• Write a program that reads order.txt (format: Beef Mushroom
pizza_name#number_of_order#price_per_pan) 2 * 85000 = 170000
and writes bill.txt. Use a structure to create
the program. Hawaiian Chicken
2 * 75000 = 150000
order.txt
Beef Mushroom#2#85000 Tuna Delight
Hawaiian Chicken#2#75000 1 * 120000 = 120000
Tuna Delight#1#120000
Mexican Sizzler#1#130000 Mexican Sizzler
1 * 130000 = 130000

Total = 570000
THANK YOU
Don t Study Hard, Study Smart.
-Amy Lucas-

You might also like