KEMBAR78
programming in C and Datastructures deepdive | PPTX
PROGRAMMING IN C AND
DATA STRUCTURES
UNIT I
UNIT II
DATA TYPES
1.Primitive Data Types
2.Derived Types
3.User Defined Data Types
USER-DEFINED DATATYPES
• The data 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
TYPES OF USER-DEFINED DATATYPES
1.Structure
2.Union
3.Enum
4.Typedef
STRUCTURE
Structures are used to 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;
....
....
};
struct Person
{
char company[50];
int lifespan;
};
int main()
{
struct Person person1;
strcpy(person1.company, "GeeksforGeeks");
person1.lifespan = 30;
printf("Name: %sn", person1.company);
printf("Age: %dn", person1.lifespan);
return 0;
struct Student
{
char name[50];
int age;
float marks;
};
int main() {
struct Student students[3] =
{
{"Nikhil", 20, 85.5},
{"Shubham", 22, 90.0},
{"Vivek", 25, 78.0}
};
for (int i = 0; i < 3; i++) {
printf("Student %d:n", i+1);
printf("Name: %sn", students[i].name);
printf("Age: %dn", students[i].age);
printf("Marks: %.2fnn",
students[i].marks);
}
return 0; }
ARRAY OF STRUCTURE
PASSING A STRUCTURE AS 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
USING CALL BY VALUE 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;
}
USING CALL BY VALUE 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;
}
USING CALL BY REFERENCE METHOD
struct student
{
char name[50];
int roll;
float marks;
};
void display(struct student* student_obj)
{
printf("Name: %sn", student_obj->name);
printf("Roll: %dn", student_obj->roll);
printf("Marks: %fn", student_obj->marks);
}
int main()
{
struct student st1 = { "Aman", 19, 8.5 };
display(&st1);
return 0;
}
USING CALL BY REFERENCE METHOD
struct student
{
char name[50];
int roll;
float marks;
};
void display(struct student* student_obj)
{
printf("Name: %sn", student_obj->name);
student_obj->roll=21;
printf("Roll: %dn", student_obj->roll);
printf("Marks: %fn", student_obj->marks);
}
int main()
{
struct student st1 = { "Aman", 19, 8.5 };
display(&st1);
printf("Inside Mainn");
printf("Name: %sn", st1.name);
printf("Roll: %dn", st1.roll);
printf("Marks: %fn", st1.marks);
return 0;
}
RETURN A STRUCTURE FROM FUNCTIONS
struct student {
char name[20];
int age;
float marks;
};
struct student get_student_data()
{
struct student s;
scanf("%s", s.name);
scanf("%d", &s.age);
scanf("%f", &s.marks);
return s; }
int main()
{
struct student s1 = get_student_data();
printf("Name: %sn", s1.name);
printf("Age: %dn", s1.age);
printf("Marks: %.1fn", s1.marks);
return 0;
}
struct student
{
char name[48];
int roll;
float marks;
};
void display(struct student* student_obj)
{
printf("Name: %sn", student_obj->name);
student_obj->roll=21;
printf("Roll: %dn", student_obj->roll);
printf("Marks: %fn", student_obj->marks);
}
int main()
{
struct student st1 = { "Aman", 19, 8.5 };
display(&st1);
printf("sizeof Structure %ldn",sizeof(st1));
printf("Size of Interger%ld",sizeof(int));
printf("Size of float%ld",sizeof(float));
printf("Name: %sn", st1.name);
printf("Roll: %dn", st1.roll);
printf("Marks: %fn", st1.marks);
return 0;
}
SIZE OF STRUCTURE
WHY PADDING HAPPENS
Most compilers 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
A nested structure in 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.
#include <stdio.h>
#include <string.h>
struct Employee
{
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
#include <stdio.h>
#include <string.h>
struct Organisation
{
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
UNION
union is a user-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.
union A
{
int i;
float f;
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);
}
#include <stdio.h>
union A
{
int x;
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;
}
UNIT II
WHY DO WE NEED 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
TEXT FILES
• A text 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.
BINARY FILES
A binary file 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.
FILE POINTER IN C
• FILE* pointer_name;
Open a File in C
FILE* fopen(const char *file_name, const char *access_mode);
C FILE OPERATIONS
1.Creating a 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()
Opening Modes in Standard 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.
r+ Open for both 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.
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;
}
CREATE A FILE IN 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;
}
READING FROM A FILE
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.
int fgetc(FILE * fp);
#include <stdio.h>
int main(){
FILE *fp ;
char ch ;
fp = fopen ("file1.txt", "r");
while(1) {
ch = fgetc (fp);
if (ch == EOF)
break;
printf ("%c", ch);
}
printf ("n");
fclose (fp);
}
int fgetc(FILE * fp);
# include <stdio.h>
int main()
{
FILE *fp;
char *string;
fp = fopen ("file2.txt", "r");
while (!feof(fp))
{
fgets(string, 256, fp);
printf ("%s", string) ;
}
fclose (fp);
}
fgets()
FILE * fptr;
fptr = fopen(“fileName.txt”, “r”);
fscanf(fptr, "%s %s %s %d", str1, str2, str3, &year);
char c = fgetc(fptr);
#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, ...)
WRITE TO A FILE
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.
#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);
#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);
FILE *fptr ;
fptr = fopen(“fileName.txt”, “w”);
fprintf(fptr, "%s %s %s %d", "We", "are", "in", 2012);
fputc("a", fptr);
Closing a File
fclose(file_pointer);
int fprintf(int c, 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);
THE PUTW() FUNCTION
fp = fopen ("num.txt", "w");
for (i =1; i<= 10; i++)
{
putw (i, fp);
}
fclose (fp);
THE GETW() FUNCTION
The getw( ) function is used for reading a number from a file
int getw (FILE *fp);
FILE *fp;
int num;
num = getw(fp);
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);
FREAD()
fread( & structure variable, 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);
FWRITE()
fwrite( & structure variable , 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);
FREAD(), FWRITE()
#include<stdio.h>
struct student{
int sno;
char sname [30];
float marks;
char temp;
};
int main ( )
{
struct student s[60];
int i;
FILE *fp;
fp = fopen ("student1.txt", "w");
for (i=0; i<2; i++){
printf ("enter details of student %d ", i+1);
printf("student number:");
scanf("%d",&s[i].sno);
scanf("%c",&s[i].temp);
printf("student name:");
gets(s[i].sname);
printf("student marks:");
scanf("%f",&s[i].marks);
fwrite(&s[i], sizeof(s[i]),1,fp);
}
fp = fopen ("student1.txt", "r");
for (i=0; i<2; i++){
printf ("details of student %d are ", i+1);
fread (&s[i], sizeof (s[i]) ,1,fp);
printf("student number = %d ", s[i]. sno);
printf("student name = %s ", s[i]. sname);
printf("marks = %f ", s[i]. marks);
}
fclose(fp);
getch( );

programming in C and Datastructures deepdive

  • 1.
    PROGRAMMING IN CAND DATA STRUCTURES
  • 2.
  • 3.
  • 4.
    DATA TYPES 1.Primitive DataTypes 2.Derived Types 3.User Defined Data Types
  • 5.
    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
  • 6.
    TYPES OF USER-DEFINEDDATATYPES 1.Structure 2.Union 3.Enum 4.Typedef
  • 7.
    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;
  • 9.
    struct Student { char name[50]; intage; float marks; }; int main() { struct Student students[3] = { {"Nikhil", 20, 85.5}, {"Shubham", 22, 90.0}, {"Vivek", 25, 78.0} }; for (int i = 0; i < 3; i++) { printf("Student %d:n", i+1); printf("Name: %sn", students[i].name); printf("Age: %dn", students[i].age); printf("Marks: %.2fnn", students[i].marks); } return 0; } ARRAY OF STRUCTURE
  • 10.
    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; }
  • 13.
    USING CALL BYREFERENCE METHOD struct student { char name[50]; int roll; float marks; }; void display(struct student* student_obj) { printf("Name: %sn", student_obj->name); printf("Roll: %dn", student_obj->roll); printf("Marks: %fn", student_obj->marks); } int main() { struct student st1 = { "Aman", 19, 8.5 }; display(&st1); return 0; }
  • 14.
    USING CALL BYREFERENCE METHOD struct student { char name[50]; int roll; float marks; }; void display(struct student* student_obj) { printf("Name: %sn", student_obj->name); student_obj->roll=21; printf("Roll: %dn", student_obj->roll); printf("Marks: %fn", student_obj->marks); } int main() { struct student st1 = { "Aman", 19, 8.5 }; display(&st1); printf("Inside Mainn"); printf("Name: %sn", st1.name); printf("Roll: %dn", st1.roll); printf("Marks: %fn", st1.marks); return 0; }
  • 15.
    RETURN A STRUCTUREFROM FUNCTIONS struct student { char name[20]; int age; float marks; }; struct student get_student_data() { struct student s; scanf("%s", s.name); scanf("%d", &s.age); scanf("%f", &s.marks); return s; } int main() { struct student s1 = get_student_data(); printf("Name: %sn", s1.name); printf("Age: %dn", s1.age); printf("Marks: %.1fn", s1.marks); return 0; }
  • 16.
    struct student { char name[48]; introll; float marks; }; void display(struct student* student_obj) { printf("Name: %sn", student_obj->name); student_obj->roll=21; printf("Roll: %dn", student_obj->roll); printf("Marks: %fn", student_obj->marks); } int main() { struct student st1 = { "Aman", 19, 8.5 }; display(&st1); printf("sizeof Structure %ldn",sizeof(st1)); printf("Size of Interger%ld",sizeof(int)); printf("Size of float%ld",sizeof(float)); printf("Name: %sn", st1.name); printf("Roll: %dn", st1.roll); printf("Marks: %fn", st1.marks); return 0; } SIZE OF STRUCTURE
  • 17.
    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; }
  • 26.
  • 27.
    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.
  • 38.
    int fgetc(FILE *fp); #include <stdio.h> int main(){ FILE *fp ; char ch ; fp = fopen ("file1.txt", "r"); while(1) { ch = fgetc (fp); if (ch == EOF) break; printf ("%c", ch); } printf ("n"); fclose (fp); } int fgetc(FILE * fp);
  • 39.
    # include <stdio.h> intmain() { FILE *fp; char *string; fp = fopen ("file2.txt", "r"); while (!feof(fp)) { fgets(string, 256, fp); printf ("%s", string) ; } fclose (fp); } fgets()
  • 40.
    FILE * fptr; fptr= fopen(“fileName.txt”, “r”); fscanf(fptr, "%s %s %s %d", str1, str2, str3, &year); char c = fgetc(fptr);
  • 41.
    #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);
  • 45.
    FILE *fptr ; fptr= fopen(“fileName.txt”, “w”); fprintf(fptr, "%s %s %s %d", "We", "are", "in", 2012); fputc("a", fptr); Closing a File fclose(file_pointer); int fprintf(int c, FILE *fp);
  • 46.
    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);
  • 52.
    FREAD(), FWRITE() #include<stdio.h> struct student{ intsno; char sname [30]; float marks; char temp; }; int main ( ) { struct student s[60]; int i; FILE *fp; fp = fopen ("student1.txt", "w");
  • 53.
    for (i=0; i<2;i++){ printf ("enter details of student %d ", i+1); printf("student number:"); scanf("%d",&s[i].sno); scanf("%c",&s[i].temp); printf("student name:"); gets(s[i].sname); printf("student marks:"); scanf("%f",&s[i].marks); fwrite(&s[i], sizeof(s[i]),1,fp); }
  • 54.
    fp = fopen("student1.txt", "r"); for (i=0; i<2; i++){ printf ("details of student %d are ", i+1); fread (&s[i], sizeof (s[i]) ,1,fp); printf("student number = %d ", s[i]. sno); printf("student name = %s ", s[i]. sname); printf("marks = %f ", s[i]. marks); } fclose(fp); getch( );