0% found this document useful (0 votes)
7 views35 pages

04.structures, Files

The document provides an overview of C programming focusing on structures, file management, and preprocessors. It covers the basics of structures, their advantages, and how to use them with functions and arrays, as well as file operations including creation, reading, and writing. Additionally, it explains the role of the C preprocessor and its directives for enhancing code readability and efficiency.
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)
7 views35 pages

04.structures, Files

The document provides an overview of C programming focusing on structures, file management, and preprocessors. It covers the basics of structures, their advantages, and how to use them with functions and arrays, as well as file operations including creation, reading, and writing. Additionally, it explains the role of the C preprocessor and its directives for enhancing code readability and efficiency.
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

CS2001 – C Programming

Structures, File Management and


Preprocessors

DR. SANJAY BANKAPUR


ASSISTANT PROFESSOR
DEPT. OF CSE
NIT PUDUCHERRY

CS2001 – C PROGRAMMING 1
Topics
❑ Structures:
❑ Basic of Structures
❑ Structures and functions
❑ Array of structures
❑ Structure data types

❑ File Management:
❑ Opening and closing of files
❑ Input and output operations

❑ Introduction to preprocessors, compiler control directives.

CS2001 – C PROGRAMMING 2
Structures in C
• A structure is a key word that create user defined data type in C.
• A structure creates a data type that can be used to group items of possibly different types into a
single type.

CS2001 – C PROGRAMMING 3
Structures in C -- Basic of Structures
• A structure is a user defined data type in C.
• A struct is keyword creates a data type that can be used to group items of possibly different
types into a single type.
• Example: struct.c
struct student
{
// A variable declaration like basic data types
char name[50];
int rollno;
int sem;
};

CS2001 – C PROGRAMMING 4
Structures in C -- Basic of Structures
• A structure is a user defined data type in C.
• A struct is keyword creates a data type that can be used to group items of possibly different
types into a single type.
• Example: struct.c
struct student struct faculty
{ {
// A variable declaration like basic data types // A variable declaration like basic data types
char name[50]; char name[50];
int rollno; char department[3];
int sem; int sem;
}; };

CS2001 – C PROGRAMMING 5
Structures in C -- Basic of Structures
• Advantages of Structure as a Data Type:
• Heterogeneous collection of data items:
• Maintainability of code
• Enhanced code readability
• Reduced complexity
• Increased productivity

CS2001 – C PROGRAMMING 6
Structures in C -- Structures & Functions
• Similar to variables of built-in types, we can also pass structure variables to a function and
return the structure variable from function.
• Passing structs to user-defined function: pass_Struct_byVal1.c
• Return structs from user-defined function: return_Struct_byVal1.c

CS2001 – C PROGRAMMING 7
Structures in C -- Array of Structures
• Similar to array of various primitive datatypes, we can also have array of user-defined data-type
i.e., array of structures.
• Example: arrayofstruct.c

CS2001 – C PROGRAMMING 8
File Management in C
• Understanding File Operations
• Modes, Functions, and Examples
• Error Handling & Best Practices

CS2001 – C PROGRAMMING 9
File - Introduction
• File
handling allows programs to store and retrieve data
permanently.
• Uses the standard library <stdio.h>
• Two file handling approaches:
• Text files
• Binary files

CS2001 – C PROGRAMMING 10
File Management in C – Why Files?
• Data Preservation: Storing data in files helps to preserve data even if the
program terminates.
• Easy Data Access: Accessing data becomes easy when there is a large amount of
data and it is stored in the file, then this data can be accessed using the C
commands.
• Portability: It becomes easier to move data from one computer to another
without any changes.

CS2001 – C PROGRAMMING 11
File Operations
• In C, we can perform four major operations on files:
• Creating a new file
• Opening an existing file
• Closing a file
• Reading from and writing information to a file

CS2001 – C PROGRAMMING 12
File Handling Functions
Key functions:
• fopen() - open a file
• fclose() - close a file
• fprintf(), fscanf() - formatted I/O
• fgets(), fputs() - string I/O
• fread(), fwrite() - binary I/O
• fseek(), ftell() - file positioning
• feof(), ferror() - file status

CS2001 – C PROGRAMMING 13
File Opening Modes
Mode Meaning
"r" Read (file must exist)
"w" Write (creates or overwrites)
"a" Append
"r+" Read + Write
"w+" Read + Write (overwrite)
"a+" Read + Append
"rb", "wb", "ab" Binary modes

CS2001 – C PROGRAMMING 14
File Opening Modes

CS2001 – C PROGRAMMING 15
File Management in C

CS2001 – C PROGRAMMING 16
File Management in C

CS2001 – C PROGRAMMING 17
File Management in C

CS2001 – C PROGRAMMING 18
File - Opening
Working with files:
• When working with files, we need to declare a pointer of type file. This declaration is
needed for communication between the file and the program.
FILE *fptr;

Opening a file - for creation and edit:


• Opening a file is performed using the fopen() function defined in the stdio.h header
file.
• The syntax for opening a file in standard I/O is:
fptr = fopen("fileopen","mode");

CS2001 – C PROGRAMMING 19
File - Opening
Working with files:
• When working with files, we need to declare a pointer of type file. This declaration is
needed for communication between the file and the program.
FILE *fptr;

Opening a file - for creation and edit:


• Opening a file is performed using the fopen() function defined in the stdio.h header
file.
• The syntax for opening a file in standard I/O is:
fptr = fopen("filename","mode");

CS2001 – C PROGRAMMING 20
File Management in C
Working with files:
• For example:
fopen("E:\\NITPy\\File-Programs\\File_Input.txt","r");
fopen("E:\\NITPy\\File-Programs\\File_Output.txt","w");
• Let's suppose the file File_Input.txt exists in the location E:\NITPy\File-Programs. The
first function opens the existing file for reading in read mode 'r’.
• Let's suppose the File_Output.txt doesn't exist in the location E:\NITPy\File-Programs.
The Second function creates a new file named [Link] and opens it for writing
as per the mode 'w’.
• The writing mode allows you to create and edit (overwrite) the contents of the file.

CS2001 – C PROGRAMMING 21
File Management in C
Working with files:
• Closing a File:
• The file (both text and binary) should be closed after reading/writing.
• Closing a file is performed using the fclose() function.
• fclose(fptr);
• Here, fptr is a file pointer associated with the file to be closed.

CS2001 – C PROGRAMMING 22
File Management in C
Working with files:
Reading and writing to a text file:
• For reading and writing to a text file, we use the functions fprintf() and fscanf().
• They are just the file versions of printf() and scanf(). The only difference is that fprintf()
and fscanf() expects a pointer to the structure FILE.
• Example 1: Write to a text file -- write_file.c
• Example 2: Read from a text file -- read_file.c

CS2001 – C PROGRAMMING 23
File Management in C
Working with files:
Getting data using fseek():
• If you have many records inside a file and need to access a record at a specific position, you
need to loop through all the records before it to get the record.
• This will waste a lot of memory and operation time. An easier way to get to the required data
can be achieved using fseek().
• As the name suggests, fseek() seeks the cursor to the given record in the file.
• Syntax of fseek():
• fseek(FILE * stream, long int offset, int position);
• pointer: pointer to a FILE object that identifies the stream.
• offset: number of bytes to offset from position
• position: position from where offset is added.

CS2001 – C PROGRAMMING 24
File Management in C

CS2001 – C PROGRAMMING 25
File Management in C
Working with files:
Getting data using fseek():
• Example: fseek_file.c

CS2001 – C PROGRAMMING 26
Preprocessor Directives in C
• C provides many features like structures, unions and pointers. Another unique feature
of the C language is the preprocessor. The C preprocessor provides several tools that
are not present in other high-level languages.
• The programmer can use these tools to make his program easy to read, easy to modify,
portable and more efficient. The preprocessor is a program that processes the source
code before it passes through the compiler.
• Preprocessor directives are placed in the source program before the main line. Before
the source code passes through the compiler, it is examined by the preprocessor for any
preprocessor directives. If there are any, appropriate actions are taken and then the
source program is handed over to the compiler.

CS2001 – C PROGRAMMING 27
Unique Feature - The C Preprocessor
• One special feature of C is the Preprocessor.
• It offers tools that many other high-level languages do not provide.
• The preprocessor works before the actual compilation begins.

CS2001 – C PROGRAMMING 28
Why Do We Need the Preprocessor?
• Helps make programs:
• Easy to read
• Easy to modify
• More portable
• More efficient
•It automates tasks that would otherwise require manual changes.

CS2001 – C PROGRAMMING 29
What is Preprocessor?
• The preprocessor is a program that:
• Processes the source code
• Before it goes to the compiler
• It handles instructions called preprocessor directives.
• Special instructions written in the source code.
• They are processed before the main() function.
• They usually begin with the symbol #
• Examples: #include, #define, #ifdef

CS2001 – C PROGRAMMING 30
Preprocessor Directives in C
• All the preprocessor directives follow special syntax rules that are different from the
normal C syntax.
• Every preprocessor directive begins with the symbol # and is followed by the respective
preprocessor directive.
• The preprocessor directives are divided into below mentioned categories:
• Macro Substitution Directives
• Compiler Control Directives

CS2001 – C PROGRAMMING 31
Preprocessor Directives in C
Macro Substitution Directives:
• Macro substitution is a process where an identifier in a program is replaced by a
predefined string composed of one or more tokens.
• The preprocessor accomplishes this task under the direction of #define statement.
• This statement, usually known as a macro definition takes the following form:
• Ex: Macros1.c, Macros2.c

#define MAX 99999999


#define PI 3.142
#define circleArea(r) (PI*r*r)

CS2001 – C PROGRAMMING 32
Preprocessor Directives in C
Macro Substitution Directives: Ex - Macros3.c

CS2001 – C PROGRAMMING 33
Preprocessor Directives in C
Compiler Control Directives:
• Following are the compiler control directives:
• Ex: Compiler1.c, Compiler2.c, Compiler3.c

CS2001 – C PROGRAMMING 34
Preprocessor Directives in C
Compiler Control Directives:
• Group-A lines are included if the customer ABC is defined. Otherwise, Group-B lines are
included.

CS2001 – C PROGRAMMING 35

You might also like