Files
Files
File is a set of records that can be accessed through the set of library functions.
There are two types of files, namely
Sequential file
Random Access file
Sequential File:-
•In this type records are kept sequentially.
•If we want to read the last record of the file , then we need to read all the
records before that record.
Random Access File:-
•In this type data can be read and modified randomly.
•In this type , if we want to read the last records of the file, we can read it
directly.
•It takes less time as compared to sequential file
‘C’ supports a number of functions that
have the ability to perform basic file
operations such as
• Naming a file
• Opening a file
• Reading data from a file
• Writing data to a file
• Closing a file
• File handling is one of the most important
parts of programming. In C, we use a structure
pointer of a file type to declare a file:
• FILE *fp;
File Handling functions
C provides a number of build-in function to perform basic file operations:
• fopen() - create a new file or open a existing file
• fclose() - close a file
• getc() - reads a character from a file
• putc() - writes a character to a file
• fscanf() - reads a set of data from a file
• fprintf() - writes a set of data to a file
• getw() - reads a integer from a file
• putw() - writes a integer to a file
• fseek() - set the position to desire point
• ftell() - gives current position in the file
• rewind() - set the position to the beginning point
Opening a file
• fseek()
• ftell()
• rewind()
fseek():
This function is used to move the file position to a desired location within
the file. It takes the following form.
fseek (file-ptr, offset, position);
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr; // use appropriate location if you are using MacOS or Linux
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
Read from a text file
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen("C:\\program.txt","r")) == NULL)
{
printf("Error! opening file"); // Program exits if the file
pointer returns NULL.
exit(1);
}
fscanf(fptr,"%d", &num);
printf("Value of n=%d", num);
fclose(fptr);
return 0;
}
Ex pgm on fseek()
#include <stdio.h>
void main(){
FILE *fp;
fp = fopen("myfile.txt","w+");
fputs("This is javatpoint", fp);
int main()
{
FILE *fp;
fp = fopen("test.txt", "r");
return 0;
}
Output:
81
• The file test.txt contains the following text:
fclose(fp);
return 0;
}
OUTPUT:
Before fseek – Fresh2refresh.com is a
programming tutorial website
After SEEK_SET to 21 – a programming tutorial
website
After SEEK_CUR to -10 – sh.com is a
programming tutorial website
After SEEK_END to -7 – website