Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

UNIT IV

1. What is a file? What are the different file opening modes in C?

A file is a collection of data stored on a secondary device like hard disk.


Declaring a file pointer variable
FILE *file_pointer_name;
FILE *fp;
fp = fopen (“in.txt", "r”);
fp = fopen (“out.txt", "w”);

MODE DESCRIPTION
r Open text file in read mode
Read only • If file exits, the marker is positioned at beginning.
• If file doesn’t exist, error returned
w Open text file in write mode.
Write only • If file exits, the previous data is erased and positioned at beginning.
• If file doesn’t exist, it is created.

a Open text file in append mode


Append Only • If file exits, the marker is positioned at end.
• If file doesn’t exist, it is created.

r+ Opens text file for reading as well as writing modes.


Read and Write
w+
Write and Read Opens text file for writing as well as reading modes.

a+
Append and Read Opens text file for reading as well as appending modes.

rb Open a binary file for reading.


read binary
wb open a binary file for writing, if it exists, it is overwritten.
write binary
ab Append to a binary file.
append binary
r+b/rb+ open a binary file for read/write
read and write
w+b/wb+ create a binary file for read/write
write and read
a+b/ab+ append a binary file for read/write. If the file does not exist, it
append and read will be created.
2. Discuss fscanf() and fprintf() functions with a suitable example

Reading From Files: fscanf ()

fscanf (stream_pointer,”format string”, list);

❖The first argument is the stream pointer, is the pointer to the streams that has been declared and
associated with a text file.

int rno, m;
FILE *fp;
fp = fopen (“mydata.txt", "r”);
fscanf (fp, "%d %d", &rno, &m);

The only difference between scanf and fscanf is that scanf reads data from the stdin (input stream)
and fscanf reads input from a user specified stream(stdin or file).

fscanf (stdin,”%d”, &a);

Writing To Files: fprintf ()

fprintf (stream_pointer, ”format string”, list);

❖Where stream_pointer is a file pointer associated with a file that has been opened for writing.

int rno = 5, m = 20;


FILE *fp;
fp = fopen (“results.txt", "w”);
fprintf (fp, "%d %d\n", rno, m) ;

PROGRAM:

#include<stdio.h>
int main()
{
FILE *fp;
int num;
char name[20];
int m;
fp = fopen("student.txt","w");
printf("Enter RollNum,name,marks\n");

while((fscanf(stdin,"%d%s%d",&num,name,&m))!=EOF)
{
fprintf(fp,"%d%s%d\n",num,name,m);
}
fclose(fp);
return 0;
}

OUTPUT
Enter RollNum,name,marks
670 JOHN 76
870 KUMAR 67

3. Write a C program to count no of lines, words and characters in a file

#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char filename[100];
char ch;
int linecount, wordcount, charcount;
linecount = 0;
wordcount = 0;
charcount = 0;
printf("Enter a filename :");
scanf(“%s”,filename);
fp = fopen(filename,"r");

if (fp== NULL)
{
puts("Could not open files");
exit(0);
}

while ((ch=getc(fp)) != EOF)


{
if (ch != ' ' && ch != '\n') { ++charcount; }
if (ch == ' ' || ch == '\n') { ++wordcount; }
if (ch == '\n') { ++linecount; }
}

if (charcount > 0)
{
printf("Lines : %d \n", ++ linecount);
printf("Words : %d \n", wordcount);
printf("Characters : %d \n", charcount);
}
return 0;
}

in.txt

Hello welcome

OUTPUT

Enter a filename :in.txt


Lines : 1
Words : 2
Characters : 12

4. Explain major file operations in C

File Operations

1. Creation of 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 or fgetc)
4. Writing to a file (fprintf or fputs or fputc)
5. Moving to a specific location in a file (fseek, rewind)
6. Closing a file (fclose)

Program:

#include<stdio.h>
int main()
{
FILE *f1,*f2; // file pointer declaration
char ch;
f1 = fopen("in.txt","r"); // opening a file in read mode
if(f1==NULL) // if file not found report an error message
printf("File does not exist");
else
{
f2 = fopen("out.txt","w"); // opening a file in write mode
while((ch=fgetc(f1))!=EOF) // reading a character till EOF
{
fputc(ch,f2); // writing character into a file
}
}
fclose(f1);
fclose(f2);
return 0;
}

in.txt

Hello Welcome

OUTPUT

out.txt

Hello Welcome

5. Explain the differences between a text file and binary file

Text file(ASCII file) – used to store human readable characters as a rich text document or plain
text document. Text files also store data in sequential bytes but bits in text file represents
characters.
Binary file-contains any type of data encoded in binary form for computer storage and
processing purpose.

S.NO TEXT FILE BINARY FILE


Type of data Contains textual data Contain both textual and custom
(ASCII format) binary data.
Handling of a newline character is No conversion takes place
newlines converted into the carriage
return-linefeed
combination before being
written to the disk
Representation Special character is Number of character in the
of end of file included to mark EOF directory
Storage of Number stored as string of Each number occupy same number
numbers character of bytes on disks
Modes r,w,a rb.wb,ab

6. Write a C program to create and display a file

#include<stdio.h>
int main()
{
FILE *f1,*f2;
char ch;
f1 = fopen("in.txt","r");
if(f1==NULL)
printf("File does not exist");
else
{
f2 = fopen("out.txt","w");
while((ch=fgetc(f1))!=EOF)
{
fputc(ch,f2);
}
}
fclose(f1);
fclose(f2);
return 0;
}

Hello Welcome

OUTPUT

out.txt

Hello Welcome

7. Write a program to copy contents one file to the other file

#include<stdio.h>
int main()
{
FILE *f1,*f2;
char ch;
f1 = fopen("in.txt","r");
if(f1==NULL)
printf("File does not exist");
else
{
f2 = fopen("out.txt","w");
while((ch=getc(f1))!=EOF)
{
putc(ch,f2);
}
}
fclose(f1);
fclose(f2);
return 0;
}
Hello Welcome

OUTPUT

out.txt

Hello Welcome

8. Write Short notes on structure? Take suitable example wherever necessary

A structure is a collection of data items of different data types stored under a common name.
Syntax:
struct structure_name
{
datatype structure_element1;
datatype structure_element2;
…………….
…………….
datatype structure_elementn;
};

#include<stdio.h>
struct student
{
int no;
char name[10];
int m1,m2,m3;
}s;
void main()
{
float total,avg;
printf("rollno:");
scanf("%d",&s.no);
printf("name:");
scanf("%s",s.name);
printf("three marks");
scanf("%d%d%d",&s.m1,&s.m2,&s.m3);
total=s.m1+s.m2+s.m3;
avg=total/3;
printf("total=%f avg=%f", total,avg);
}
OUTPUT:
rollno: 1
name: raji
three marks 78 78 78
total= 234.000000
avg= 78.000000

9. Declare a structure for employee entity with suitable attributes? Initialize employee structure
variable. Write the statements to display all the details using pointer.

#include<stdio.h>
struct employee
{
char empname[10];
int empid;
float salary;
};

void main()
{
struct employee e,*emp;
emp=&e;
printf("enter empname, empid, salary\n");
scanf("%s%d%f",emp->empname,&emp->empid,&emp->salary);
printf("Employee name is %s \n",(*emp).empname);
printf("Employee id is %d \n",(*emp).empid);
printf("Employee salary is %f \n",(*emp).salary);

OUTPUT
enter empname, empid, salary
arun
1000
20000
Employee name is arun
Employee id is 1000
Employee salary is 20000.000000

10. With suitable examples compare structure and union. Create a union as part of a structure.

#include<stdio.h>
union doj
{
int dd;
int mon;
int year;
};
struct employee
{
char empname[10];
int empid;
float salary;
union doj dat;
};

void main()
{
struct employee emp;
printf("enter empname, empid, salary, date of joining\n");
scanf("%s%d%f%d%d
%d",emp.empname,&emp.empid,&emp.salary,&emp.dat.dd,&emp.dat.mon,&emp.dat.year);
printf("Employee name is %s \n",emp.empname);
printf("Employee id is %d \n",emp.empid);
printf("Employee salary is %f \n",emp.salary);
printf("Employee day is %d \n",emp.dat.dd);
printf("Employee month is %d \n",emp.dat.mon);
printf("Employee year is %d \n",emp.dat.year);

}
OUTPUT

enter empname, empid, salary, date of joining


arun
123
89097
12
12
2022
Employee name is arun
Employee id is 123
Employee salary is 89097.000000
Employee day is 2022 Employee day is 12
Employee month is 2022 Employee month is 12
Employee year is 2022 Employee year is 2022

11. Write a C program to print maximum marks in each subject along with the name of the
student by using structures. Take 3 subjects and 3students records.

#include<stdio.h>

struct stud
{
char name[10];
int id;
int m[3];
}s[3];

int main()

int i;
for(i=0;i<3;i++)
{
printf("Enter Name ID M1 M2 M3 of student:%d\n",i+1);
scanf("%s%d%d%d%d",s[i].name,&s[i].id,&s[i].m[0],&s[i].m[1],&s[i].m[2]);
}
printf("Name ID M1 M2 M3 of students are\n");

for(i=0;i<3;i++)
{
printf("%s\t%d\t%d\t%d\t%d\n",s[i].name,s[i].id,s[i].m[0],s[i].m[1],s[i].m[2]);
}
for(i=0;i<3;i++)
greaterMarks(i);
return 0;
}

void greaterMarks(int i)
{
printf("From sub:%d among 3 students\n",i+1);

if(s[0].m[i]>s[1].m[i]&&s[0].m[i]>s[2].m[i])
{
printf("%d is greater\n",s[0].m[i]);
}
else if(s[1].m[i]>s[0].m[i]&&s[1].m[i]>s[2].m[i])
{
printf("%d is greater\n",s[1].m[i]);
}
else if(s[2].m[i]>s[0].m[i]&&s[2].m[i]>s[1].m[i])
{
printf("%d is greater\n",s[2].m[i]);
}
}

Output

Enter Name ID M1 M2 M3 of student:1

arun 1 67 78 65

Enter Name ID M1 M2 M3 of student:2

ram 2 78 65 67

Enter Name ID M1 M2 M3 of student:3

sriram 3 98 56 67

Name ID M1 M2 M3 of students are

arun 1 67 78 65

ram 2 78 65 67

sriram 3 98 56 76

From sub:1 among 3 students

sriram got 98 is greater


From sub:2 among 3 students

arun scored 78 is greater

From sub:3 among 3 students

sriram got 76 is greater

You might also like