0% found this document useful (0 votes)
15 views

C - Data Structures+IO

The document discusses different C structural data types including enums, structs, unions, and bit fields. Enums define a data type consisting of a set of named integer constants, structs allow grouping of different data types together, and unions and bit fields allow optimizing memory usage. The document also covers input/output streams for programs to communicate with devices and files.

Uploaded by

Nguyễn Dương
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

C - Data Structures+IO

The document discusses different C structural data types including enums, structs, unions, and bit fields. Enums define a data type consisting of a set of named integer constants, structs allow grouping of different data types together, and unions and bit fields allow optimizing memory usage. The document also covers input/output streams for programs to communicate with devices and files.

Uploaded by

Nguyễn Dương
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Chapter 4: Structural data type

1
Content

• 4.1. Enum
• 4.2. Struct
• 4.3. Union and Bit Fields

2
4. 1. Enumeration type

• Enumeration is a user defined datatype in C


• whose range is a number of certain values that can be listed
• Definition of an enumeration
• Syntax 1: enum <type_name> { <list of values> };
• enum Animal { Cat, Dog, Tiger, Lion };
• enum dayInWeek {Mo, Tu, We, Th, Fr, Sa, Su};
• enum gender {M, F};

• Syntax 2: typedef enum {<list of values> } <type_name>;


• typedef enum {True, False} boolean;

3
4. 1. Enumeration type

• Enumeration variables
• Declaration and usage
• enum dayInWeek {Mo, Tu, We, Th, Fr, Sa, Su};
• enum dayInWeek dv;
• dv = We;

• enum dayInWeek {Mo, Tu, We, Th, Fr, Sa, Su} dv;
• dv = We;

• enum dayInWeek {Mo, Tu, We, Th, Fr, Sa, Su} dv;
• dv = We;

• typedef enum {True, False} boolean;


• boolean dv;
• dv = True;

4
4. 1. Enumeration type

• Enumeration variables
• Corresponding Values
• by default: integer constants: 0, 1, 2, ….
• can be explicitly set when defining.

• typedef enum {True, False} boolean;


• typedef enum {True=1, False=0} boolean;
• enum Colors {BLUE=1,RED=3,GREEN=2} c;

5
Example

0 1 2 3 4 5 6 7 8 9 10 11

1, 0, 0

6
Example

1 2 5 6 10 11 12

7
4.2. Struct type

• A complex type containing data components of different types


• Definition of a struct type
• Syntax 1: struct <name> {
< data_components>
};

• Example:
• struct Student {
char name[20];
Do not initialize
int dob; components here!
int major;
};

8
4.2. Struct type

• A complex type containing data components of different types


• Definition of a struct type
• Syntax 2: typedef struct {
< data_components>
} <name>;

• Example:
• typedef struct {
char name[20];
int dob; Do not initialize
int major; components here!
} Student;

9
4.2. Struct type

• Struct type variables


• Declaration
• struct Student { typedef struct {
char name[20]; char name[20];
int dob; int dob;
int major;
int major;
} Student;
};
Student sv1, sv2;
struct Student sv1, sv2;

struct Student {
char name[20];
int dob;
int major;
} sv1, sv2;

10
4.2. Struct type

• Struct type variables


• Usage:
struct Student { struct Student sv1; //error: expected expression
char name[20]; sv1 = {"Le Duc Tho", 1984, 56}; before ‘{’ token
int dob;
int major; struct Student sv1 = {"Le Duc //OK
}; Tho", 1984, 56};

typedef struct { Student sv1; //error: expected expression


char name[20]; sv1 = {"Le Duc Tho", 1984, 56}; before ‘{’ token
int dob;
int major; Student sv1 = {"Le Duc Tho", 1984, 56}; //OK
} Student;

struct Student {
char name[20]; int dob; int major; //OK
} sv1 = {"Le Duc Tho", 1984, 56};

11
4.2. Struct type

• Struct type variables


• Usage:
• access operator .
• access operator ->
Assignment
typedef struct {
char ID[30] ; class lh1, lh2;
char major; lh1=lh2;
int quantity;
} class ;
class lh;
lh1.ID = lh2.ID;
class * p = &lh;
lh1.major= lh2.major;
lh1.quantity = lh2.quantity;
scanf(“%s”, lh.ID);
scanf(“%c”, &p->major);
scanf(“%d”, &p->quantity);
(*p).major = ‘A’;

12
Example

13
Combination

• It is possible to define a combination

typedef struct {
char name[20];
unsigned int age;
enum {Nam, Nu} gender;
struct {
char city[20];
char street[20];
int number;
} address;
} Student;

14
4.3. Union and Bit Fields

• Structure types to save storage size


• Union structure:
• like struct, but components are stored in the same memory box
• the memory box for a union is equal to the size of it’s largest component
• used in certain scenarios where you want to use only one of the components at a time.

union char_and_ascii
{
char ch;
unsigned short ascii_val;
};

union char_and_ascii obj;


obj.ascii_val = 0;
obj.ch = 'A';
printf("character = [%c], ascii_value = [%u]\n", obj.ch, obj.ascii_val);

//character = [A], ascii_value = [65]

15
4.3. Union and Bit Fields

• Union structure:
union SOME_TYPES {
char character;
short shortinteger;
int integer;
} my_space;
my_space.integer = 0x12345678; // little endian: 78563412
// my_space.character = ? // = 0x78
// my_space.shortinteger = ? // = 0x5678

union
{
int integer; h.integer = 0x12345678;
struct h.Bytes.firstByte = ?
{ h.Bytes.secondByte = ?
char firstByte;
char secondByte;
// = 0x78
char thirdByte;
// = 0x56
char fourthByte;
} Bytes;
} h ;

16
4.3. Union and Bit Fields

• Bit field structure: is a struct, but fields can declare storage size up to
the bit level (1 or more bits) to reduce memory consumption (speed is
slow however)
• Type for bit field: unsigned int, signed int, or int
• address-of operator (&), sizeof cannot be applied to bit-field components

struct example1 typedef struct


{ {
int isMemoryAllocated; int bit_0: 1;
int isObjectAllocated; int bit_1: 1;
}; int bit_2: 1;
int bit_3: 1;
struct example2 int bit_4: 1;
{ int bit_5: 1;
int isMemoryAllocated : 1; int bit_6: 1;
int isObjectAllocated : 1; int bit_7: 1;
}; } bits;
#define PORTA (*((bits*) 0xFFFF0000))
PORTA.bit_0 = 1;

17
Input/Output

18
Concept

• To work with a number of input and output devices such as monitors,


keyboards, files, printers, etc…
• Stream:
• An intermediary medium for communication (receiving/ sending information)
between the program and the device
 To receive/send information for a device, we will send/ receive information
for the stream connected to that device (device independent)
• Stream is a sequence of data bytes
• “Flow” into the program is called the input stream.
• “Flow” out of the program is called output stream.

19
Concept

• Streams for each program:


• stdout: standard output, default is console screen
• stderr: standard error output, defaults is console, used to display error lines
• stdin: standard input, default is keyboard

Name Stream Device


stdin Standard input keyboard
stdout Standard output screen
stderr Standard error output screen
stdprn (MS-DOS) Standard printer Printer (LPT1:)
stdaux (MS-DOS) Standard auxiliary Serial port COM 1:

20
Concept

• The program also works with files on the computer: .TXT, .EXE,
.JPG, .DOC, .PPT, …
• File:
• A collection of information (data) organized in a certain form (format)
with a definite name.
• A continuous byte sequence (from a storage perspective).
• Stored in external storage devices such as floppy disks, hard disks, USB...
• Persists when the program ends.
• Unlimited size (depending on storage device)
• Program allows to read data (input device) and write data (output
device) on the file.

21
Concept

• Text style file


• The sequence of consecutive lines containing readable characters
• Each line ends with the end-of-line symbol ‘\n’
• In Windows: ‘\n’ = CR character (ASCII 13) + LF (ASCII 10)
• In Linux: ‘\n’ = LF
• Binary file
• Contains data bytes.
• Each binary file type will have its own format: header (metadata) + data (in its
own structure)

22
Work with stdout/stdin

int putchar(int c);


int puts(const char* s);
int printf(const char* format, ...);
int getchar();
char* gets(char* s);
int scanf(const char* format, ...);

23
Work with files

• Create explicit streams to connect to the specified file.


• Stream classification in C:
• Text stream (for text files)
• Contain characters, organized into lines
• Each line ends with the end-of-line symbol '\n', not '\0'.
• Binary Stream (for binary files)
• Contains bytes.
• Data is read and written exactly byte by byte, with no conversion at all.
• The line terminator '\n' is treated like any other data byte.
• Can process any data, including text data.

24
Open a file

• FILE type in <stdio.h>


• File operation sequence: Open/create file  Read/write data  Close
• In the FILE type, there is a field that stores information about the reading / writing
position of the file, called the file pointer
• Open file:
• FILE* fopen(const char* fname, const char* mode);

mode Meaning mode Meaning


"r" Read only "r+" Read and write
"w" Write only, delete the old file's "w+" Read and write, delete the old
content if it exists or create a new file's content if it exists or create a
file if it doesn't exist new file if it doesn't exist
"a" Write only, point the pointer to the "a+" Read and write point the pointer
end of the file to continue writing to the end of the file to continue
or create a new file if it doesn't writing or create a new file if it
exist doesn't exist
"t" in text mode "b" in binary mode

25
Open a file

• The file opening may fail and return NULL  need to check the return value
of fopen()
• Possible reasons for file opening failure:
• Open the file to read but the file does not exist
• The current user has no permissions
• The file is being opened in restricted mode by a certain program
• There are too many open files at the same time (limitation of OS)

26
Open files and limit reopening

• Sometimes we don't want other programs to interfere with a file we


are opening to read/write
• FILE* _fsopen(const char* fname, const char*
mode, int shflag);
• shflag: flags allow the file to be reopened or not
• #include <share.h>

shflag Meaning
_SH_DENYNO Unlimited
_SH_DENYRD re-opened with reading mode
_SH_DENYWR re-opened with writing mode
_SH_DENYRW re-opened with reading mode and writing mode

• Note: This function is only available in MS Visual C

27
Read/write a file

• Write text data:


• int fputc(int c, FILE* file);
• int fputs(const char* s, FILE* file);
• int fprintf(FILE* file, const char* format, ...);
• Use as the functions: putchar(), puts(), printf()
• Read text data:
• int fgetc(FILE* file);
• char *fgets(char* s, int n, FILE* file);
• int fscanf(FILE* file, const char* format, ...);
• Use as the functions getchar(), gets(), scanf() but returns EOF if reaching the
end of file.

28
Read/write a file

• Write binary data :


• int fwrite(const void* buf, int size, int count,
FILE* file);
• Write an array with count elements, each element's size is size

• Read binary data:


• int fread(void* buf, int size, int count, FILE*
file);
• Read an array with count elements, each element's size is size

• Because reading/writing files uses a buffer, it is often necessary to use the fflush()
function to “clean” the buffer before switching from write to read (if opening the
file in read and write mode simultaneously)
• int fflush(FILE* file);

29
Read/write a file

• Check the end of the file or not? :


• int feof(FILE* file);
• Close file:
• int fclose(FILE* file);
• Delete file:
• int remove(const char* path);
• Rename file:
• int rename(const char* old, const char* new);

30
Work with Stream

• fprintf function outputs the specified stream


• Output to the screen : fprintf(stdout, “Hello”);
• Output to printer: fprintf(stdprn, “Hello”);
• Output to error device: fprintf(stderr, “Hello”);
• Output file (stream fp): fprintf(fp, “Hello”);

31
Example

32
Example

33
Example

int copy_file(const char* src, const char* dst) {


FILE *fs = NULL, *fd = NULL;
char buf[1024];
int num;

if ((fs = fopen(src,"rb")) == NULL) return -1;


if ((fd = fopen(dst,"wb")) == NULL) { fclose(fs); return -1; }

while(!feof(fs)) {
num = fread(buf, 1, sizeof(buf), fs);
fwrite(buf, 1, num, fd);
}

fclose(fs); fclose(fd);
return 0;
}

34
Location of file pointer

• Automatically generated when opening the file.


• Determine where the read/write takes place in the file
• Pointer position
• When the file is not open: at the beginning of the file (value 0)
• When opening the file:
• mode a or a+: at the end of the file
• Other modes (w, w+, r, r+): at the beginning of the file (value 0)
• The function works with position pointers
• Specify the current position : long ftell(FILE* file);
• Move the cursor to the beginning of the file : void rewind(FILE* file);
• Move the cursor in the file :
int fseek(FILE* file, long offset, int org);
org = 1 = SEEK_CUR: count from current position
org = 2 = SEEK_END: count from the end of the file
org = 0 = SEEK_SET: count from the beginning of the file

35
Example

#include <stdio.h>

int main () {
FILE *fp;

fp = fopen("file.txt","w+");
fputs("This is tutorialspoint.com", fp);

fseek( fp, 7, SEEK_SET );


fputs(" C Programming Language", fp);
fclose(fp);

return(0);
}

36
stdin, stdout, stderr

• Standard I/O is actually predefined FILE* variables, so reading/ writing with


printf(…), scanf(…) is equivalent to fprintf(stdout,…) and fscanf(stdin,...)
• Functions putchar(), puts(), getchar(), gets() also perform read/write on stdin and
stdout
• Standard I/O Redirection:
Sign Meaning
command > file Print to file, instead of stdout, create a new file or delete the
command 1> file old file if there is one
command 2> file Print to file, instead of stderr, create a new file or delete the
old file if there is one
command >> file Print to file, instead of stdout, and continue writing at the end
command 1>> file of that file
command 2>> file Print to file, instead of stderr, and continue writing at the end
of that file
command < file Read from file, instead of stdin
command1 | command2 Redirect stdout of command1 as stdin of command2

37
Read/write on memory

• Write:
• sprintf(char* buffer, const char* format, ...);
• Read:
• sscanf(const char* buffer, const char* format,
...);
• Similar to fprintf() and fscanf(), but the data is stored in a specified
memory area in the buffer parameter.
• Example:
• char s[50];
sprintf(s, "sin(pi/3) = %.3f", sin(3.14/3));
• Result: s will contain string "sin(pi/3) = 0.866"

38
Bài tập

1. Khai báo một kiểu dữ liệu cấu trúc miêu tả các thông tin của một chiếc ôtô có
các thuộc tính: model, khối lượng, màu sơn, 4 bánh trong đó mỗi bánh có
thuộc tính: chủng loại, bán kính, khối lượng. Cho phép người dùng nhập dữ
liệu cho 1 chiếc ô tô và in thông tin chiếc ô tô ra màn hình.
2. Định nghĩa mảng chứa các hàm tính sin, cos, tan của một góc, sử dụng cấu trúc
struct MenuItem {Tiêu đề, Hàm xử lý }. In ra màn hình các tiêu đề tương ứng
của các hàm, nhận lựa chọn của người dùng và thực hiện gọi hàm tương ứng
3. Định nghĩa kiểu struct Shape rồi viết hàm tính diện tích, chu vi của hình tuỳ
theo dạng của nó. Dùng 2 cách: switch và con trỏ hàm

39
Bài tập xử lý File

1. Viết chương trình nối một file vào sau một file hiện tại
2. Viết chương trình in ra dòng thứ 10 của một file
3. Viết chương trình chèn một dòng vào dòng thứ 10 của một file (ghi nội
dung sau chèn ra 1 file mới)
4. Viết một hàm trả về kích thước của một file

40
Exercises

1. Declare a structured data type describing the information of a car


with attributes: model, mass, paint color, 4 wheels in which each
wheel has attributes: type, radius, mass. Allows users to enter
data for a car and print the car's information on the screen.
2. Define an array containing functions that calculate the sin, cos,
and tan of an angle, using the struct MenuItem {Title, Handler}
structure. Print to the screen the respective titles of the
functions, get the user selection and call the corresponding
function
3. Define a struct Shape type and then write a function to calculate
the area and perimeter of the shape depending on its shape. Use
2 ways: switch and function pointer

41
Exercises on File processing

1. Write a program to append a file after the current file


2. Write a program to print the 10th line of a file
3. Write a program to insert a line into the 10th line of a file (write output to a
new file)
4. Write a function that returns the size of a file

42

You might also like