Unit 12
File Management in ‘C’
- What is declaration of file pointer give example?
The C library function int fseek(FILE *stream, long int offset, int whence) sets the file position of the stream to the given offset.
Declaration
Following is the declaration for fseek() function.
Int fseek(FILE *stream, long int offset, int whence)
Parameters
- Stream − This is the pointer to a FILE object that identifies the stream.
- Offset − This is the number of bytes to offset from whence.
- Whence − This is the position from where offset is added. It is specified by one of the following constants −
Sr.No. | Constant & Description |
1 | SEEK_SET Beginning of file |
2 | SEEK_CUR Current position of the file pointer |
3 | SEEK_END End of file |
Return Value
This function returns zero if successful, or else it returns a non-zero value.
Example
The following example shows the usage of fseek() function.
#include <stdio.h>
Int main () {
FILE *fp;
fp = fopen("file.txt","w+");
fputs("This is tutorialspoint.com", fp);
fseek( fp, 7, SEEK_SET );
fputs(" C Programming Language", fp);
fclose(fp);
return(0);
}
Let us compile and run the above program that will create a file file.txt with the following content. Initially program creates the file and writes This is tutorialspoint.com but later we had reset the write pointer at 7th position from the beginning and used puts() statement which over-write the file with the following content −
This is C Programming Language
Now let's see the content of the above file using the following program −
#include <stdio.h>
Int main () {
FILE *fp;
int c;
fp = fopen("file.txt","r");
while(1) {
c = fgetc(fp);
if( feof(fp) ) {
break;
}
printf("%c", c);
}
fclose(fp);
return(0);
}
Let us compile and run the above program to produce the following result −
This is C Programming Language
2. Explain in brief Opening Files
You can use the fopen( ) function to create a new file or to open an existing file. This call will initialize an object of the type FILE, which contains all the information necessary to control the stream. The prototype of this function call is as follows −
FILE *fopen( const char * filename, const char * mode );
Here, filename is a string literal, which you will use to name your file, and access mode can have one of the following values −
Sr.No. | Mode & Description |
1 | r Opens an existing text file for reading purpose. |
2 | w Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file. |
3 | a Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content. |
4 | r+ Opens a text file for both reading and writing. |
5 | w+ Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist. |
6 | a+ Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended. |
If you are going to handle binary files, then you will use following access modes instead of the above mentioned ones −
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"
3. Explain in brief Closing a File
To close a file, use the fclose( ) function. The prototype of this function is −
Int fclose( FILE *fp );
The fclose(-) function returns zero on success, or EOF if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.
There are various functions provided by C standard library to read and write a file, character by character, or in the form of a fixed length string.
4. What is a Binary file?
Binary files are very similar to arrays of structures, except the structures are in a disk-file rather than an array in memory. Binary files have two features that distinguish them from text files:
- You can instantly use any structure in the file.
- You can change the contents of a structure anywhere in the file.
After you have opened the binary file, you can read and write a structure or seek a specific position in the file. A file position indicator points to record 0 when the file is opened.
A read operation reads the structure where the file position indicator is pointing to. After reading the structure the pointer is moved to point at the next structure.
A write operation will write to the currently pointed-to structure. After the write operation the file position indicator is moved to point at the next structure.
The fseek function will move the file position indicator to the record that is requested.
Remember that you keep track of things, because the file position indicator can not only point at the beginning of a structure, but can also point to any byte in the file.
The fread and fwrite function takes four parameters:
- A memory address
- Number of bytes to read per block
- Number of blocks to read
- A file variable
For example:
fread(&my_record,sizeof(struct rec),1,ptr_myfile);
This fread statement says to read x bytes (size of rec) from the file ptr_myfile into memory address &my_record. Only one block is requested. Changing the one into ten will read in ten blocks of x bytes at once.
5. What is C File management?
A File can be used to store a large volume of persistent data. Like many other languages 'C' provides following file management functions,
- Creation of a file
- Opening a file
- Reading a file
- Writing to a file
- Closing a file
Following are the most important file management functions available in 'C,'
Function | Purpose |
Fopen () | Creating a file or opening an existing file |
Fclose () | Closing a file |
Fprintf () | Writing a block of data to a file |
Fscanf () | Reading a block data from a file |
Getc () | Reads a single character from a file |
Putc () | Writes a single character to a file |
Getw () | Reads an integer from a file |
Putw () | Writing an integer to a file |
Fseek () | Sets the position of a file pointer to a specified location |
Ftell () | Returns the current position of a file pointer |
Rewind () | Sets the file pointer at the beginning of a file |
6. How to Create a File
Whenever you want to work with a file, the first step is to create a file. A file is nothing but space in a memory where data is stored.
To create a file in a 'C' program following syntax is used,
FILE *fp;
Fp = fopen ("file_name", "mode");
In the above syntax, the file is a data structure which is defined in the standard library.
Fopen is a standard function which is used to open a file.
- If the file is not present on the system, then it is created and then opened.
- If a file is already present on the system, then it is directly opened using this function.
Fp is a file pointer which points to the type file.
Whenever you open or create a file, you have to specify what you are going to do with the file. A file in 'C' programming can be created or opened for reading/writing purposes. A mode is used to specify whether you want to open a file for any of the below-given purposes. Following are the different types of modes in 'C' programming which can be used while working with a file.
File Mode | Description |
r | Open a file for reading. If a file is in reading mode, then no data is deleted if a file is already present on a system. |
w | Open a file for writing. If a file is in writing mode, then a new file is created if a file doesn't exist at all. If a file is already present on a system, then all the data inside the file is truncated, and it is opened for writing purposes. |
a | Open a file in append mode. If a file is in append mode, then the file is opened. The content within the file doesn't change. |
r+ | Open for reading and writing from beginning |
w+ | Open for reading and writing, overwriting a file |
a+ | Open for reading and writing, appending to file |
In the given syntax, the filename and the mode are specified as strings hence they must always be enclosed within double quotes.
7. Write a C File Example: Storing employee information
Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.
- #include <stdio.h>
- Void main()
- {
- FILE *fptr;
- Int id;
- Char name[30];
- Float salary;
- Fptr = fopen("emp.txt", "w+");/* open for writing */
- If (fptr == NULL)
- {
- Printf("File does not exists \n");
- Return;
- }
- Printf("Enter the id\n");
- Scanf("%d", &id);
- Fprintf(fptr, "Id= %d\n", id);
- Printf("Enter the name \n");
- Scanf("%s", name);
- Fprintf(fptr, "Name= %s\n", name);
- Printf("Enter the salary\n");
- Scanf("%f", &salary);
- Fprintf(fptr, "Salary= %.2f\n", salary);
- Fclose(fptr);
- }
Output:
Enter the id
1
Enter the name
Sonoo
Enter the salary
120000
Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.
Emp.txt
Id= 1
Name= sonoo
Salary= 120000
8. Give some of the functions with example
C fputc() and fgetc()
Writing File : fputc() function
The fputc() function is used to write a single character into file. It outputs a character to a stream.
Syntax:
- Int fputc(int c, FILE *stream)
Example:
- #include <stdio.h>
- Main(){
- FILE *fp;
- Fp = fopen("file1.txt", "w");//opening file
- Fputc('a',fp);//writing single character into file
- Fclose(fp);//closing file
- }
File1.txt
Reading File : fgetc() function
The fgetc() function returns a single character from the file. It gets a character from the stream. It returns EOF at the end of file.
Syntax:
- Int fgetc(FILE *stream)
Example:
- #include<stdio.h>
- #include<conio.h>
- Void main(){
- FILE *fp;
- Char c;
- Clrscr();
- Fp=fopen("myfile.txt","r");
- While((c=fgetc(fp))!=EOF){
- Printf("%c",c);
- }
- Fclose(fp);
- Getch();
- }
Myfile.txt
This is simple text message
9. Write into a file in file handling
Se the code to get the idea how we write into a file
Example Code
#include <stdio.h>
Int main() {
FILE *fp;
Char *filename = "sample.txt";
Char *content = "Hey there! You've successfully created a file with content in c programming language.";
/* open for writing */
Fp = fopen(filename, "w");
If( fp == NULL ) {
Printf("%s: failed to open. \n", filename);
Return -1;
} else {
Printf("%s: opened in write mode.\n", filename);
}
/* Write content to file */
Fprintf(fp, "%s\n", content);
If( !fclose(fp) )
Printf("%s: closed successfully.\n", filename);
Return 0;
}
Output
Sample.txt: opened in write mode.
Sample.txt: closed successfully.
10. Appending into a file in file handling. Explain
Se the code to get the idea how we can append lines into a file.
Make a file (file_append.txt)
This text was already there in the file.
Example Code
#include <stdio.h>
Int main() {
FILE *fp;
Char ch;
Char *filename = "file_append.txt";
Char *content = "This text is appeneded later to the file, using C programming.";
/* open for writing */
Fp = fopen(filename, "r");
Printf("\nContents of %s -\n\n", filename);
While ((ch = fgetc(fp) )!= EOF) {
Printf ("%c", ch);
}
Fclose(fp);
Fp = fopen(filename, "a");
/* Write content to file */
Fprintf(fp, "%s\n", content);
Fclose(fp);
Fp = fopen(filename, "r");
Printf("\nContents of %s -\n", filename);
While ((ch = fgetc(fp) )!= EOF) {
Printf ("%c", ch);
}
Fclose(fp);
Return 0;
}
Output
Contents of file_append.txt -
This text was already there in the file.
Appending content to file_append.txt...
Content of file_append.txt after 'append' operation is -
This text was already there in the file.
This text is appeneded later to the file, using C programming.