Está en la página 1de 13

Data Files

 A file is a place on the disk where a group of related data is stored.

Why files are needed?


 When a program is terminated, the entire data is lost. Storing in a file will preserve
your data even if the program terminates.
 If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents
of the file using few commands in C.
 You can easily move your data from one computer to another without any changes.

Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
1. Text files
 Text files are the normal .txt files that you can easily create using Notepad or any
simple text editors.
 When you open those files, you'll see all the contents within the file as plain text.
 You can easily edit or delete the contents.
 They take minimum effort to maintain, are easily readable, and provide least security
and takes bigger storage space.

2. Binary files
 Binary files are mostly the .bin files in your computer.
 Instead of storing data in plain text, they store it in the binary form (0's and 1's).
 They can hold higher amount of data, are not readable easily and provides a better
security than text files.

File Operations
In C, you can perform four major operations on the file, either text or binary:
1. Creating a new file
2. Opening an existing file
3. Closing a file
4. Reading data from a file
5. Writing data to a file

Working with files


When working with files, you need to declare a pointer of type file. This declaration is
needed for communication between the file and program.

FILE *fptr

Opening a file
Opening a file is performed using the library function in the "stdio.h" header file: fopen().
The syntax for opening a file in standard I/O is:
ptr = fopen("filename","mode")
For Example:
fopen("E:\\cprogram\\newprogram.txt","w");

fopen("E:\\cprogram\\oldprogram.bin","rb");

File 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.
If the file exists, its contents are overwritten. If the
w Open for writing.
file does not exist, it will be created.
If the file exists, its contents are overwritten. If the
wb Open for writing in binary mode.
file does not exist, it will be created.
Open for append. i.e., Data is added to
a If the file does not exists, it will be created.
end of file.
Open for append in binary mode. i.e.,
ab If the file does not exists, it will be created.
Data is added to end of file.
r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.
Open for both reading and writing in
rb+ If the file does not exist, fopen() returns NULL.
binary mode.
If the file exists, its contents are overwritten. If the
w+ Open for both reading and writing.
file does not exist, it will be created.
Open for both reading and writing in If the file exists, its contents are overwritten. If the
wb+
binary mode. file does not exist, it will be created.
a+ Open for both reading and appending. If the file does not exists, it will be created.
Open for both reading and appending in
ab+ If the file does not exists, it will be created.
binary mode.

Closing a File
The file (both text and binary) should be closed after reading/writing. Closing a file is
performed using library function fclose().
fclose(fptr); //fptr is the file pointer associated with file to be closed.
Input/output Operation on files

Writing File : fputc() function


 The fputc() function is used to write a single character into file. It outputs a character
to a stream.
 Syntax: fputc( ch, filepointer). This function writes the character variable ch to the
files associated with file pointer.
Reading File : fgetc() function
 The fgetc() function is used to read a single character from a file. It gets a character
from the stream. It returns EOF at the end of file.
 Syntax: ch=fgetc(filepointer).

Example.
#include <stdio.h>
#include<conio.h>
int main() {
int i; char ch; FILE *fp;

fp = (fopen("C:\\Users\\User\\Desktop\\cexamples\\getput.txt", "w"));
if(fp == NULL)
{
printf("Error!");
exit(1);
}

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


{
Printf(“\n Enter a character : ”)
scanf(" %c",&ch);
fputc(ch ,fp);//writing single character into file
}
fclose(fp);//closing file

fp = (fopen("C:\\Users\\User\\Desktop\\cexamples\\getput.txt", "r"));
while((ch=fgetc(fp))!=EOF){
printf(" %c",ch);
}
fclose(fp);
getch();
return 0;
}
Writing File : fputs() function
 The fputs() function writes a line of characters into file. It outputs string to a stream.
 Syntax: fputc( str, filepointer). This function writes line of character i.e. str to the
files associated with file pointer.

Reading File : fgets() function


 The fgets() function reads a line of characters from file. It gets string from a stream.
 Syntax: fgets(str, Max_length, filepointer). Max_length is the maximum length of
string str.

Example.
#include <stdio.h>
#include<conio.h>
int main() {
int i; char txt[80]; FILE *fp;

fp = (fopen("C:\\Users\\User\\Desktop\\cexamples\\getputs.txt", "w"));
if(fp == NULL)
{
printf("Error!");
exit(1);
}

// loop to input 5 line of text.


for(i = 0; i < 5; ++i)
{
printf(“\n Enter a line of text : ”);
gets(txt);
fputs(txt ,fp);//writing single character into file
fputs("\n " ,fp);
}
fclose(fp);//closing file

fp = (fopen("C:\\Users\\User\\Desktop\\cexamples\\getputs.txt", "r"));
while(fgets(txt,79,fp)!=NULL){
printf("\n %s",txt);
}
fclose(fp);
getch();
return 0;
}
WAP to write line of text to “source.txt” and copy the content of file “source.txt” to
another file “destination.txt” character wise.

#include <stdio.h>
#include<conio.h>
int main() {
int i; char txt[100],ch; FILE *fp1, *fp2;

fp1 = (fopen("C:\\Users\\User\\Desktop\\cexamples\\source.txt", "w"));

if(fp1 == NULL)
{
printf("Error!");
exit(1);
}

// loop to input 5 line of text.


for(i = 0; i < 5; ++i)
{
printf("\n Enter a line of text : ");
gets(txt);
fputs(txt ,fp1);//writing single character into file
fputs("\n " ,fp1);
}
fclose(fp1);//closing file

fp1 = (fopen("C:\\Users\\User\\Desktop\\cexamples\\source.txt", "r"));


fp2 = (fopen("C:\\Users\\User\\Desktop\\cexamples\\destination.txt","w"));

while((ch=fgetc(fp1))!=EOF){
fputc(ch,fp2);
}

fclose(fp1);
fclose(fp2);

getch();
return 0;
}

fprintf() and fscanf()


Writing File : fprintf() function
 The fprintf() function is used to write set of characters into file. It sends formatted
output to a stream.
 Syntax: fprintf(filepointer, “Control Strings”,list);
Reading File : fscanf() function
 The fscanf() 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: fprintf(filepointer, “Control Strings”, &list);

Write a C program to read name and marks of n number of students from user and store
them in a file. Display the content of file onto the screen.

#include <stdio.h>
int main(){
char name[50]; int marks, i, num;

printf("Enter number of students: ");


scanf("%d", &num);

FILE *fptr;
fptr = (fopen("C:\\Users\\User\\Desktop\\cexamples\\student.txt", "w"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}

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


{
printf("For student%d\nEnter name: ", i+1);
scanf(" %s", name);

printf("Enter marks: ");


scanf(" %d", &marks);

fprintf(fptr,"\n Name: %s \n Marks=%d ", name, marks);


}
fclose(fptr);

fptr = (fopen("C:\\Users\\User\\Desktop\\cexamples\\student.txt", "r"));

while((fscanf(fptr," %s ", name))!=EOF){


printf(" %s", name);

}
fclose(fptr);
//getch();
return 0;
}
Reading and writing to a binary file/ unformatted data files
Functions fread() and fwrite() are used for reading from and writing to a file on the disk
respectively in case of binary files.

fwrite(&var, sizeof(var), 1, filepointer);


fread(&var, sizeof(var), 1, filepointer);

Random Access to File using fseek() and ftell() functions


 fseek() function is used to move the file position to a desired location within the file.
 It takes the following form:
 fseek(filepointer, offset, Position);
 The first parameter stream is the pointer to the file. The second parameter is the
position of the record to be found, and the third parameter specifies the location where
the offset starts.

Different parameter in fseek

Whence Meaning

SEEK_SET Starts the offset from the beginning of the file.

SEEK_END Starts the offset from the end of the file.

SEEK_CUR Starts the offset from the current location of the cursor in the file.

 Ftell(): takes a file pointer & returns a number of type long, that corresponds to the
current position.
 Syntax: n=ftell(filepointer);

 Rewind(): takes a file pointer and resets the position to the start of the file.
 Syntax: rewind(filepointer);

Fseek() Example
1. Fseek(fp, 0, SEEK_SET): go to the beginning of file.
2. Fseek(fp, -m, SEEK_CUR): go backward by m bytes from the current
position.
3. Fseek(fp, 0, SEEK_END): go to the end of the file.
4. Fseek(fp, -m, SEEK_END): go backward by m bytes from the end of file.
//Write a C program to read name age and crn of students from user until user type YES.
//Store these records in a file. Read the content from file and Display onto the screen.

#include <stdio.h>
#include <string.h>
#include <conio.h>
struct Student
{
int age;
char name[30];
int crn;
};

int main()
{
char txt[5];
struct Student s1;
FILE *fptr;

if ((fptr = fopen("C:\\Users\\User\\Desktop\\cexamples\\binary.txt","wb+")) == NULL){


printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
// enter data until user say YES
do
{
printf("\n Enter name: ");
scanf(" %s", s1.name);

printf("\n Enter age: ");


scanf(" %d", &s1.age);

printf("\n Enter rollnumber: ");


scanf(" %d", &s1.crn);

fwrite(&s1, sizeof(s1), 1, fptr);

printf("Do you want to another record YES/NO");


scanf(" %s",txt);

}while((strcmp("YES",txt))==0);

//rewind(fptr);
fseek(fptr, 0, SEEK_SET);

while(fread(&s1,sizeof(s1),1,fptr)>0)
{
printf("\n Name: %s",s1.name);
printf("\n Age:%d",s1.age);
printf("\n Roll Number: %d",s1.crn);
}

fclose(fptr);
getch();
return 0;
}

//Write a C program to read name age and crn of students from user until user type YES.
//Store these records in a file. Read n from the user and display nth record from file.

#include <stdio.h>
#include <string.h>
#include <conio.h>
struct Student
{
int age;
char name[30];
int crn;
};

int main()
{
char txt[5];
struct Student s1;
FILE *fptr;
int n, count=0;

if ((fptr = fopen("C:\\Users\\User\\Desktop\\cexamples\\binary.txt","wb+")) ==
NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
// enter data until user say YES
do
{
printf("\n Enter name: ");
scanf(" %s", s1.name);

printf("\n Enter age: ");


scanf(" %d", &s1.age);

printf("\n Enter rollnumber: ");


scanf(" %d", &s1.crn);

fwrite(&s1, sizeof(s1), 1, fptr);

printf("Do you want to another record YES/NO");


scanf(" %s",txt);

}while((strcmp("YES",txt))==0);

//rewind(fptr);
fseek(fptr, 0, SEEK_SET);

printf("\n Enter n to display nth record from file: ");


scanf(" %d", &n);

while(fread(&s1,sizeof(s1),1,fptr)>0)
{
count ++;

if(n==count)
{
printf("\n Name: %s",s1.name);
printf("\n Age:%d",s1.age);
printf("\n Roll Number: %d",s1.crn);
}
}

fclose(fptr);
getch();
return 0;
}

// program to read the data of employee until the user wishes to stop. Write this data to file.
//Read the data from file, sort the employee based on salary and rank. Finally read the data
//from the file and print the information along rank.

#include<stdio.h>
#include<conio.h>

struct Employee
{
char name[20];
int sal;
int rank;
};

int main()
{
struct Employee e,e1[20],e2[20],temp;
FILE *fp1, *fp2;
int i,j,count=0;
char txt[5];

fp1=fopen("C:\\Users\\User\\Desktop\\cexamples\\employee.txt", "w+");

if(fp1==NULL)
{
printf("Cannot create the file");
exit(1);
}
do
{
printf("\nEnter the name of employee:");
scanf(" %s",e.name);

printf("\nEnter the salary of employee:");


scanf(" %d",&e.sal);

printf("\nEnter the Rank of employee:");


scanf(" %d",&e.rank);

fprintf(fp1," %s %d %d \n",e.name,e.sal, e.rank);

printf("Do you want to another record YES/NO");


scanf(" %s",txt);
}while((strcmp("YES",txt))==0);

rewind(fp1);

while(fscanf(fp1," %s %d %d ",e1[count].name,&e1[count].sal,&e1[count].rank)!=EOF)
{
count++;

for(i=0;i<count;i++)
for(j=0;j<count-1;j++)
{
if(e1[j].sal>e1[j+1].sal)
{
temp=e1[j];
e1[j]=e1[j+1];
e1[j+1]=temp;
}
}
fclose(fp1);

fp2=fopen("C:\\Users\\User\\Desktop\\cexamples\\bemployee.txt", "wb+");
if(fp2==NULL)
{
printf("Cannot create the file");
exit(1);
}
fwrite(&e1,sizeof(struct Employee),count,fp2);

rewind(fp2);

fread(&e2,sizeof(struct Employee),count,fp2);

printf("\n\nName\tSalary\tRank\n");
for(i=0;i<count;i++)
{
printf("%s\t%d\t%d \n",e2[i].name,e2[i].sal,e2[i].rank);
}

fclose(fp2);
getch();
return 0;
}

Error Handling during I/O operations


Possible errors during I/O operations on file may occur due to
 Trying to read beyond end of file mark.
 Device overflow.
 Trying to perform an operation on a file when the file is opened for another type of
operation.
 Trying to use a file that has not been opened.
 Attempting to write to a write protected file.

A program behaves abnormally when an error occurs. An unchecked error may result in a
premature termination of program or give incorrect output.

Two status enquiry library functions feof() and ferror() can help us to detect I/O errors in the
files.

feof(): used to test for an end of file condition. It takes a file pointer as an argument and
returns a non-zero integer value if all the data from the specified file has been read and
returns zero otherwise.
if( feof(fp) )
printf(“End of data”);

#here on reading the end of file condition it display the message “End of data”.

ferror(): takes file pointer as its argument and returns an non-zero integer if an error has been
detected up to that point, during processing.
if( ferror(fp) )
printf(“Error has been detected”);
Whenever a file is opened using fopen() function, a file pointer is returned. If the file cannot
be opened for some reason, then the function returns NULL pointer. It can be used to check if
a file been opened or not.
if( fp )
printf(“File cannot be opened.”);

También podría gustarte