USER-DEFINED DATATYPES
• Thedata types defined by the user themself are referred to as user-defined
data types. These data types are derived from the existing datatypes.
Need of User-Defined Datatypes
• It enables customization in the code.
• Users can write more efficient and flexible code.
• Provides abstraction
STRUCTURE
Structures are usedto group items of different types into a single
type. The "struct" keyword is used to define a structure. The size of the
structure is equal to or greater than the total size of all of its
members.
struct structure_name
{
data_type member_name1;
data_type member_name1;
....
....
};
8.
struct Person
{
char company[50];
intlifespan;
};
int main()
{
struct Person person1;
strcpy(person1.company, "GeeksforGeeks");
person1.lifespan = 30;
printf("Name: %sn", person1.company);
printf("Age: %dn", person1.lifespan);
return 0;
PASSING A STRUCTUREAS AN ARGUMENT TO THE FUNCTIONS
• By passing all the elements to the function individually.
• By passing the entire structure to the function.
Using Call By Value Method
Using Call By Reference Method
11.
USING CALL BYVALUE METHOD
struct car
{
char name[30];
int price;
};
void print_car_info(struct car c)
{
printf("Name : %s", c.name);
printf("nPrice : %dn", c.price);
}
int main()
{
struct car c = { "Tata", 1021 };
print_car_info(c);
return 0;
}
12.
USING CALL BYVALUE METHOD
struct car
{
char name[30];
int price;
};
void print_car_info(struct car c)
{
printf("Name : %s", c.name);
c.price =1050;
printf("nPrice : %dn", c.price);
}
int main()
{
struct car c = { "Tata", 1021 };
print_car_info(c);
printf("Name : %s", c.name);
printf("nPrice : %dn", c.price);
return 0;
}
WHY PADDING HAPPENS
Mostcompilers align data members in memory according to their natural size requirements for performance
optimization. Typically, int and float require alignment on 4-byte boundaries.
Memory Layout with Padding
To maintain proper alignment, the compiler inserts 2 padding bytes after name[50] so that roll starts at a memory
address divisible by 4. This results in a total structure size of 60 bytes.
Member
Size
(Bytes)
Start
Address
End Address
name[50] 50 0 49
Padding 2 50 51
roll (int) 4 52 55
marks (float) 4 56 59
18.
A nested structurein C is a structure within
structure. One structure can be declared inside
another structure in the same way structure
members are declared inside a structure.
NESTED STRUCTURE
Different ways of nesting structure
1. By separate nested structure
2. By embedded nested structure.
• By separate nested structure: In this method, the two
structures are created, but the dependent structure(Employee)
should be used inside the main structure(Organisation) as a
member.
• By Embedded nested structure: Using this method, allows
to declare structure inside a structure and it requires fewer
lines of code.
19.
#include <stdio.h>
#include <string.h>
structEmployee
{
int employee_id;
char name[20];
int salary;
};
struct Organisation
{
char organisation_name[20];
char org_number[20];
struct Employee emp;
};
int main()
{
struct Organisation org;
printf("The size of organisation %ldn",sizeof(org));
org.emp.employee_id = 101;
strcpy(org.emp.name, "Robert");
org.emp.salary = 400000;
strcpy(org.organisation_name,"GeeksforGeeks");
strcpy(org.org_number, "GFG123768");
printf("Org Name : %sn",org.organisation_name);
printf("Organisation Number : %sn",org.org_number);
printf("Employee id : %dn",org.emp.employee_id);
printf("Employee name : %sn",org.emp.name);
printf("Employee Salary : %dn",org.emp.salary);
}
By separate nested structure
20.
#include <stdio.h>
#include <string.h>
structOrganisation
{
char organisation_name[20];
char org_number[20];
struct Employee
{
int employee_id;
char name[20];
int salary;
} emp;
};
int main()
{
struct Organisation org;
printf("The size of organisation : %ldn",sizeof(org));
org.emp.employee_id = 101;
strcpy(org.emp.name, "Robert");
org.emp.salary = 400000;
strcpy(org.organisation_name,"GeeksforGeeks");
strcpy(org.org_number, "GFG123768");
printf("Org. Name : %sn",org.organisation_name);
printf("Organisation Number : %sn",org.org_number);
printf("Employee id : %dn",org.emp.employee_id);
printf("Employee name : %sn",org.emp.name);
printf("Employee Salary : %dn",org.emp.salary);
}
By embedded nested structure
21.
UNION
union is auser-defined data type that can contain elements of
the different data types just like structure.
But unlike structures, all the members in the C union are stored
in the same memory location.
Due to this, only one member can store data at the given point
in time.
22.
union A
{
int i;
floatf;
char s[20];
};
int main()
{
union A a;
a.i = 10;
printf("data.i = %d ", a.i);
a.f = 220.5;
printf("data.f = %.2f ", a.f);
strcpy(a.s, "GfG");
printf("data.s = %s ", a.s);
}
23.
#include <stdio.h>
union A
{
intx;
char y;
};
union B{
int arr[10];
char y;
};
int main() {
printf("Sizeof A: %ldn", sizeof(union A));
printf("Sizeof B: %ldn", sizeof(union B));
return 0;
}
WHY DO WENEED FILE HANDLING IN C
• So far the operations using the C program are done on a prompt/terminal which is not stored
anywhere. The output is deleted when the program is closed. But in the software industry,
most programs are written to store the information fetched from the program
• Reusability
• Portability
• Efficient
• Storage Capacity
29.
TEXT FILES
• Atext file contains data in the form of ASCII characters and is generally used to store a
stream of characters.
• Each line in a text file ends with a new line character (‘n’).
• It can be read or written by any text editor.
• They are generally stored with .txt file extension.
• Text files can also be used to store the source code.
30.
BINARY FILES
A binaryfile contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters. They
contain data that is stored in a similar manner to how it is stored in the main memory.
• The binary files can be created only from within a program and their contents can only be
read by a program.
• More secure as they are not easily readable.
• They are generally stored with .bin file extension.
31.
FILE POINTER INC
• FILE* pointer_name;
Open a File in C
FILE* fopen(const char *file_name, const char *access_mode);
32.
C FILE OPERATIONS
1.Creatinga new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
2.Opening an existing file – fopen()
3.Reading from file – fscanf() or fgets()
4.Writing to a file – fprintf() or fputs()
5.Moving to a specific location in a file – fseek(), rewind()
6.Closing a file – fclose()
33.
Opening Modes inStandard I/O
Mode Meaning of Mode During Inexistence of file
r Open for reading.
If the file does not exist, fopen() returns
NULL.
rb Open for reading in binary mode.
If the file does not exist, fopen() returns
NULL.
w Open for writing.
If the file exists, its contents are overwritten.
If the file does not exist, it will be created.
wb Open for writing in binary mode.
If the file exists, its contents are overwritten.
If the file does not exist, it will be created.
a
Open for append.
Data is added to the end of the file.
If the file does not exist, it will be created.
Open for append in binary mode.
34.
r+ Open forboth reading and writing. If the file does not exist, fopen() returns NULL.
rb+
Open for both reading and writing in binary
mode.
If the file does not exist, fopen() returns NULL.
w+ Open for both reading and writing.
If the file exists, its contents are overwritten.
If the file does not exist, it will be created.
wb+
Open for both reading and writing in binary
mode.
If the file exists, its contents are overwritten.
If the file does not exist, it will be created.
a+ Open for both reading and appending. If the file does not exist, it will be created.
ab+
Open for both reading and appending in
binary mode.
If the file does not exist, it will be created.
35.
OPENING A FILE
#include<stdio.h>
#include <stdlib.h>
int main()
{
FILE* fptr;
fptr = fopen("filename.txt", "r");
if (fptr == NULL) {
printf("The file is not opened. The program will now exit.");
exit(0);
}
return 0;
}
36.
CREATE A FILEIN C
FILE *fptr;
fptr = fopen("filename.txt", "w");
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* fptr;
fptr = fopen("file.txt", "w");
if (fptr == NULL) {
printf("The file is not opened. The program will exit now");
exit(0);
}
else { printf("The file is created Successfully."); }
return 0;
}
37.
READING FROM AFILE
Function Description
fscanf() Use formatted string and variable arguments list to take input from a file.
fgets() Input the whole line from the file.
fgetc() Reads a single character from the file.
fgetw() Reads a number from a file.
fread() Reads the specified bytes of data from a binary file.
#include <stdio.h>
int main(){
FILE *fp;
char *s;
int i, a;
float p;
fp = fopen ("file3.txt", "r");
if (fp == NULL) {
puts ("Cannot open file"); return 0;
}
while (fscanf(fp, "%d %f %s", &a, &p, s) != EOF)
printf ("Name: %s Age: %d Percent: %fn", s, a, p);
fclose(fp);
return 0;
}
int fscanf(FILE *stream, const char *format, ...)
42.
WRITE TO AFILE
Function Description
fprintf()
Similar to printf(), this function use formatted string and varible arguments list to print output
to the file.
fputs() Prints the whole line in the file and a newline at the end.
fputc() Prints a single character into the file.
fputw() Prints a number to the file.
fwrite() This functions write the specified amount of bytes to the binary file.
43.
#include <stdio.h>
int main(){
FILE *fp;
char * string = "C Programming tutorial from TutorialsPoint";
int i;
char ch;
fp = fopen("file1.txt", "w");
for (i = 0; i < strlen(string); i++)
{
ch = string[i];
if (ch == EOF)
break;
fputc(ch, fp);
}
printf ("n");
fclose(fp);
int fputc(int c, FILE *fp);
44.
#include <stdio.h>
int main(){
FILE *fp;
char *sub[] = {"C Programming n", "C++ n", "Python n", "Java n"};
fp = fopen("file2.txt", "w");
for (int i = 0; i < 4; i++) {
fputs(sub[i], fp);
}
fclose(fp);
return 0;
}
int fputs(const char *s, FILE *fp);
THE PUTW() FUNCTION
•The putw() function is used for writing a number into a file.
• This function writes binary data to a file.
• It requires two inputs: the data to be written and a pointer to the file
putw (int num, FILE *fp);
FILE *fp;
int num;
putw(num, fp);
47.
THE PUTW() FUNCTION
fp= fopen ("num.txt", "w");
for (i =1; i<= 10; i++)
{
putw (i, fp);
}
fclose (fp);
48.
THE GETW() FUNCTION
Thegetw( ) function is used for reading a number from a file
int getw (FILE *fp);
FILE *fp;
int num;
num = getw(fp);
49.
THE GETW() FUNCTION
FILE*p;
p =fopen ("num.txt", "r");
printf ("file content is");
for (i =1; i<= 10; i++){
i= getw(fp);
printf ("%d",i);
printf("");
}
fclose (fp);
50.
FREAD()
fread( & structurevariable, size of (structure variable), no of records, file pointer);
struct emp
{
int eno;
char ename [30];
float sal;
} e;
FILE *fp;
fread (&e, sizeof (e), 1, fp);
51.
FWRITE()
fwrite( & structurevariable , size of structure variable, no of records, file pointer);
struct emp
{
int eno:
char ename [30];
float sal;
} e;
FILE *fp;
fwrite (&e, sizeof(e), 1, fp);