0% found this document useful (0 votes)
3 views19 pages

C Structures and File Handling Guide

This document provides an overview of structures, unions, enumerations, and file handling in C programming. It explains how to define and use structures, including arrays of structures and passing them as function arguments, as well as the basics of file operations such as creating, reading, writing, and closing files. Additionally, it includes example code snippets for each concept to illustrate their usage.

Uploaded by

balthapa2006
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)
3 views19 pages

C Structures and File Handling Guide

This document provides an overview of structures, unions, enumerations, and file handling in C programming. It explains how to define and use structures, including arrays of structures and passing them as function arguments, as well as the basics of file operations such as creating, reading, writing, and closing files. Additionally, it includes example code snippets for each concept to illustrate their usage.

Uploaded by

balthapa2006
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

UNIT – 5

Structures: -
A structure in C is a user-defined data type that groups variables of different data
types under a single name. This allows you to create complex data structures that
represent real-world entities.
Struct keyword is used to define the structure. The items in the structure are
called its member and they can be of any valid data type. The values of a structure
are stored in contiguous memory locations.
Syntax : -
struct structure_name
{
data_type member1;
data_type member2;
// ... data_type memberN;
};

struct employee
{
int emp_code;
char emp_name[100];
char desg[100];
float salary;
}

Variable declaration;

Struct employee a;

Input data

a.emp_code = 10;

a.emp_code = “Arpan”;

[Link] = “professor”

[Link] = 50000

Example: -
#include<stdio.h>

struct employee

int emp_code;

char emp_name[50];

char desg[50];
float salary;

};

void main()

struct employee a;

printf("\nEnter employee name: ");

scanf("%s",&a.emp_name);

printf("\nEnter employee code: ");

scanf("%d",&a.emp_code);

printf("\nEnter Salary: ");

scanf("%f",&[Link]);

printf("\nEnter Designation: ");

scanf("%s",&[Link]);

printf("\nName = %s",a.emp_name);

printf("\nCode = %d",a.emp_code);

printf("\nDesignation = %s",[Link]);

printf("\nSalary = %f",[Link]);

}
Array of Structure: -
#include<stdio.h>

struct employee

int code;

char name[50];

float salary;

};

void main()

struct employee a[3];

int i, key, flag = 0, pos;

for(i=0;i<3;i++)

printf("\nEnter Name: ");

scanf (“%s”,&a[i].name);

printf("\nEnter code: ");

scanf("%d",&a[i].code);

printf("\nEnter Salary: ");

scanf("%f",&a[i].salary);

printf("\nEnter employee code to search: ");

scanf("%d",&key);

for(i=0;i<3;i++)

if(a[i].code==key)

flag=1;

pos=i;

break;

}
}

if(flag==1)

printf("\nName = %s",a[pos].name);

printf("\nCode = %d",a[pos].code);

printf("\nSalary = %f",a[pos].salary);

else

printf("\nSearch Value not found");

Structure as Function argument: -


#include<stdio.h>
struct employee

int code;

char name[50];

int salary;

};
void display(struct employee);

void main()

struct employee aa;

printf("\nEnter Name: ");

scanf("%s",&[Link]);

printf("\nEnter code: ");

scanf("%d",&[Link]);

printf("\nEnter Salary: ");

scanf("%d",&[Link]);

display(aa);

void display(struct employee x)

printf("\nName = %s",[Link]);

printf("\nCode = %d",[Link]);

printf("\nSalary = %d",[Link]);

Pointer to Structure: -
#include<stdio.h>

struct employee

int code;

char name[50];
int salary;

};

void display(struct employee *);

void main()

struct employee aa;

printf("\nEnter Name: ");

scanf("%s",&[Link]);

printf("\nEnter code: ");

scanf("%d",&[Link]);

printf("\nEnter Salary: ");

scanf("%d",&[Link]);

display(&aa);

void display(struct employee *a1)

printf("\nName = %s",a1->name);

printf("\nCode = %d",a1->code);

printf("\nSalary = %d",a1->salary);

Union: - Union is user defined datatype just like structure. It can store the data
in the same memory location. Due to this only one member can store the data at
given time.
Syntax:-
union union_name
{
datatype member1;
datatype member2;

Example: -

#include<stdio.h>
#include<string.h>
union employee

int code;

char name[50];

float salary;

};

int main()

union employee aa;

printf("\nEnter Name:");

scanf("%s",&[Link]);

printf("\nEnter Code:");

scanf("%d",&[Link]);

printf("\nEnter Salary:");

scanf("%f",&[Link]);

printf("\nCode = %d",[Link]);

printf("\nName= %s",[Link]);

printf("\nSalary = %0.2f",[Link]);

return 0;

}
Enumeration: -
Enumeration (or enum) is user defined data type in C. It is used to assign names
to integral constant, the names make a program easy to read and maintain. Enum
keyword is used to declare.

Example: -
#include<stdio.h>
enum week{Mon,Tue,Wed,Thur,Fri,Sat,Sun};
void main()
{
enum week day;
day=wed;
printf(“%d”,day);
}
Note: - Every element has initial and predefined value start from 0. We can
manually initialize value at any element or all elements.
#include<stdio.h>
enum week {Mon,Tue,Wed,Thu,Fri,Sat,Sun};
enum level {Low=5,Medium,High};
void main()
{
enum week days;
int i;
for(i=Mon;i<=Sun;i++)
{
printf("%d\n",i);
}
enum level myOne=Medium;
printf("\n%d",myOne);
}

File Handling
Introduction: -
File Handling in C is the process in which we create, open, read, write and close
operations on a file.
File handling is used to store the data permanently. The data is stored in a file,
which can be updated, accessed and deleted.
C file Operations: -
1 – Creating a file: - fopen() with attributes as ‘a’ or ‘a+’ or ‘w’ or ‘w+’.
2 – Opening and existing file: - fopen().
3 – Reading from file: - fscanf() or fgets().
4 – Writing to a file: - fprintf() or fputs().
5 – Moving a file : - fseek(), rewind().
6 – Closing a file: - fclose().

Fopen() – This function is used to open a file to perform operation such as,
reading, writing etc. We declare a file pointer and use the function fopen() to open
a file.
Syntax: -
File *fp;
fp = fopen(“filename”, ”mode”);
fp  is the file pointer to the datatype.
filename  is the name of the file with full path.
mode  in which file will be opened
fp = fopen(“[Link]”, “w”)
w  Creates new file if already exist then it delete the existing file & create a new
one with same name.
r  read mode.
a  append mode is used to update the existing file.
Fclose() – This function is used to close a file.
Syntax: -
File *fp;
fp = fopen(“filename”, “mode”);
statements
fclose(fp);
Fputc() – This function is used to write a single character into file.
Example: -
#include<stdio.h>
main()
{
File *fp;
fp=fopen(“[Link]”, “w”);
fputc(‘a’, fp);
fclose(fp);
}
Fprintf() – This function is used to write different types of data into a file pointer.
Syntax: -
File *fp;
fp=fopen(“filename”, “mode”);
---------------
---------------
fprintf(fp,”text%d”,variable_name);
fclose(fp);

Example: -
#include<stdio.h>
void main()
{
FILE *fp;
fp=fopen("[Link]","w");
fprintf(fp,"Using File Handling");
printf("\nFile Created Successfully.");
fclose(fp);
}

Fputs() – This function is used to writes a line of character into the file.
#include<stdio.h>
void main()
{
FILE *fp;
fp=fopen("[Link]","w");
fputs("hello C Programming",fp);
printf("\nFile Created Successfully.");
fclose(fp);
}

Ques : - Write a program to store details of student using file handling.


Sol: -
#include<stdio.h>
void main()
{

FILE *fptr;

int roll, marks;

char name[50];

fptr = fopen("[Link]","w");

if(fptr==NULL)

{
printf("File does not exist:\n");
}

printf("\nEnter roll no: ");

scanf("%d",&roll);

fprintf(fptr,"Roll no = %d\n",roll);

printf("\nEnter name: ");

scanf("%s",name);

fprintf(fptr,"Name = %s\n",name);

printf("\nEnter Marks: ");

scanf("%d",&marks);

fprintf(fptr,"Marks = %d\n",marks);

fclose(fptr);

}
Ques: - Multiple data entry in file.
Sol: -
#include<stdio.h>

void main()

FILE *fptr;

int roll, marks, choice;

char name[50];

fptr = fopen("[Link]","w");

if(fptr==NULL)

printf("File does not exist:\n");

while(1)

printf("\nEnter roll no: ");

scanf("%d",&roll);

fprintf(fptr,"Roll no = %d\n",roll);

printf("\nEnter name: ");

scanf("%s",name);

fprintf(fptr,"Name = %s\n",name);

printf("\nEnter Marks: ");

scanf("%d",&marks);

fprintf(fptr,"Marks = %d\n",marks);
printf("\n1->Enter More.\n 2-Exit.\nEnter Your choice: ");

scanf("%d",&choice);

if(choice==2)

break;

fclose(fptr);

printf("File Created Successfully");

Read Function: -
Fgetc() – This function returns a single character from the file. It returns EOF
when it reaches at the end of file.
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp=fopen("[Link]","r");
while((ch=fgetc(fp))!=EOF)
{
printf("%c",ch);
}
fclose(fp);
}

Ques: - WAP to count total number of Vowels & Consonant in a file?


Sol: -
#include<stdio.h>
void main()
{

FILE *fp;

char ch;

int vow=0, cons=0;

fp=fopen("[Link]","r");

while(ch!=EOF)

ch = fgetc(fp);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'||ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch
=='U')

vow++;

else

cons++;

printf("\nTotal Vowels = %d\nTotal Consonant = %d",vow,cons);

fclose(fp);

Fscanf() – This function is used to read set of characters from file. It reads a
word from the file and returns EOF at the end of file.
Syntax: -
fscanf(file_pointer, “%s”, buffer);
file_pointer  is the file pointer using which file is opened.
%s  is the conversion specification for reading string.
buffer  is the buffer memory in which the data has to be stored after reading
from the file.
Example: -
1 - #include<stdio.h>
void main()
{

FILE *fp;

char buff[255];
fp=fopen("[Link]","r");

fscanf(fp,"%s",buff);

printf("%s",buff);

fclose(fp);

2 - #include<stdio.h>
void main()
{

FILE *fp;

char buff[255];

fp=fopen("[Link]","r");

while((fscanf(fp,"%s",buff))!=EOF)

printf("%s",buff);

fclose(fp);

Fgets() – This function is used to read a file content line by line.


Syntax: -
fgets (buffer, size, fp);
Example: -
#include<stdio.h>
void main()
{

FILE *fp;

char buff[255];

fp=fopen("[Link]","r");

fgets(fp,"%s",buff);

printf("%s",buff);

fclose(fp);

Ques – WAP to copy content of one file to another file?


Sol -
#include<stdio.h>
void main()
{

FILE *fp, *fp2;

char ch;

fp = fopen("[Link]","r");

if(fp==NULL)

printf("Error opening the file");

fp2 = fopen("[Link]","w");

if(fp2==NULL)

printf("Error opening the file");


}

while(1)

ch=fgetc(fp);

if(ch==EOF)

break;

else

fputc(ch, fp2);

fclose(fp);

fclose(fp2);

printf("File Copied Successfully");

You might also like