0% found this document useful (0 votes)
30 views

File Handling in C - IBSC

The document discusses file handling in C. It explains that file handling allows a C program to create, read, update, and delete files stored on the local file system. Common file handling functions include fopen() to open a file, fprintf() and fputs() to write to a file, fscanf() and fgets() to read from a file, and fclose() to close a file. It provides an example of using these functions to store employee data in a text file, including id, name, and salary.

Uploaded by

sureshroopa2k15
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

File Handling in C - IBSC

The document discusses file handling in C. It explains that file handling allows a C program to create, read, update, and delete files stored on the local file system. Common file handling functions include fopen() to open a file, fprintf() and fputs() to write to a file, fscanf() and fgets() to read from a file, and fclose() to close a file. It provides an example of using these functions to store employee data in a text file, including id, name, and salary.

Uploaded by

sureshroopa2k15
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Q>Explain File Handling in C?

In programming, we may require some specific input data to be generated several numbers of times.
Sometimes, it is not enough to only display the data on the console. The data to be displayed may
be very large, and only a limited amount of data can be displayed on the console, and since the
memory is volatile, it is impossible to recover the programmatically generated data again and again.
However, if we need to do so, we may store it onto the local file system which is volatile and can be
accessed every time. Here, comes the need of file handling in C.

File handling in C enables us to create, update, read, and delete the files stored on the local file
system through our C program. The following operations can be performed on a file.

o Creation of the new file


o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the file

Functions for file handling


There are many functions in the C library to open, read, write, search and close the
file. A list of file functions are given below:

No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file


7 fseek() sets the file pointer to given position

8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file

Opening File: fopen()


We must open a file before it can be read, write, or update. The fopen() function is
used to open a file. The syntax of the fopen() is given below.

1. FILE *fopen( const char * filename, const char * mode );


The fopen() function accepts two parameters:

o The file name (string). If the file is stored at some specific location, then we
must mention the path at which the file is stored. For example, a file name can
be like "c://some_folder/some_file.ext".
o The mode in which the file is to be opened. It is a string.

We can use one of the following modes in the fopen() function.

Q>List file operation modes or file modes in C?

Mode Description

R opens a text file in read mode


W opens a text file in write mode

A opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode

a+ opens a text file in read and write mode

rb opens a binary file in read mode

wb opens a binary file in write mode

ab opens a binary file in append mode

rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode

ab+ opens a binary file in read and write mode

Example:
1. #include<stdio.h>
2. void main( )
3. {
4. FILE *fp ;
5. char ch ;
6. fp = fopen("file_handle.c","r") ;
7. while ( 1 )
8. {
9. ch = fgetc ( fp ) ;
10. if ( ch == EOF )
11. break ;
12. printf("%c",ch) ;
13. }
14. fclose (fp ) ;
15. }
Output
The content of the file will be printed.

#include;
void main( )
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and stored in the
character file.
if ( ch == EOF )
break;
printf("%c",ch);
}
fclose (fp );
}

Closing File: fclose()


The fclose() function is used to close a file. The file must be closed after performing
all the operations on it. The syntax of fclose() function is given below:

1. int fclose( FILE *fp );

Q>Explain different commands used for Writing data into files?


1)fprintf() 2)fputc() 3)fputs() 4)fwrite()
Writing File : fprintf() function
The fprintf() function is used to write set of characters into file. It sends formatted
output to a stream.

Syntax:
1. int fprintf(FILE *stream, const char *format [, argument, ...])
Example:

1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file.txt", "w");//opening file
5. fprintf(fp, "Hello file by fprintf...\n");//writing data into file
6. fclose(fp);//closing file
7. }
Writing File : fputc() function
The fputc() function is used to write a single character into file. It outputs a character
to a stream.

Syntax:

1. int fputc(int c, FILE *stream)


Example:

1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file1.txt", "w");//opening file
5. fputc('a',fp);//writing single character into file
6. fclose(fp);//closing file
7. }
file1.txt

Writing File : fputs() function


The fputs() function writes a line of characters into file. It outputs string to a stream.

Syntax:

1. int fputs(const char *s, FILE *stream)


Example:

1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. clrscr();
6.
7. fp=fopen("myfile2.txt","w");
8. fputs("hello c programming",fp);
9.
10. fclose(fp);
11. getch();
12. }
myfile2.txt

hello c programming

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.

1. #include <stdio.h>
2. void main()
3. {
4. FILE *fptr;
5. int id;
6. char name[30];
7. float salary;
8. fptr = fopen("emp.txt", "w+");/* open for writing */
9. if (fptr == NULL)
10. {
11. printf("File does not exists \n");
12. return;
13. }
14. printf("Enter the id\n");
15. scanf("%d", &id);
16. fprintf(fptr, "Id= %d\n", id);
17. printf("Enter the name \n");
18. scanf("%s", name);
19. fprintf(fptr, "Name= %s\n", name);
20. printf("Enter the salary\n");
21. scanf("%f", &salary);
22. fprintf(fptr, "Salary= %.2f\n", salary);
23. fclose(fptr);
24. }
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
Q>Explain different commands used for Reading data from files?
1)fscanf() 2)fgetc() 3) fgets() 4)fread()
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:

1. int fscanf(FILE *stream, const char *format [, argument, ...])


Example:

1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. char buff[255];//creating char array to store data of file
5. fp = fopen("file.txt", "r");
6. while(fscanf(fp, "%s", buff)!=EOF){
7. printf("%s ", buff );
8. }
9. fclose(fp);
10. }
Output:

Hello file by fprintf...

Reading File : fgets() function


The fgets() function reads a line of characters from file. It gets string from a stream.

Syntax:

1. char* fgets(char *s, int n, FILE *stream)


Example:

1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char text[300];
6. clrscr();
7.
8. fp=fopen("myfile2.txt","r");
9. printf("%s",fgets(text,200,fp));
10.
11. fclose(fp);
12. getch();
13. }
Output:

hello c programming

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:

1. int fgetc(FILE *stream)


Example:

1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("myfile.txt","r");
8.
9. while((c=fgetc(fp))!=EOF){
10. printf("%c",c);
11. }
12. fclose(fp);
13. getch();
14. }
myfile.txt

this is simple text message


Q>Explain different functions available in
C for selecting a record randomly?
C fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is used to
write data into file at desired location.

Syntax:

1. int fseek(FILE *stream, long int offset, int whence)


There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR
and SEEK_END.

Example:

1. #include <stdio.h>
2. void main(){
3. FILE *fp;
4. fp = fopen("myfile.txt","w+");
5. fputs("This is javatpoint", fp);
6. fseek( fp, 7, SEEK_SET );
7. fputs("sonoo jaiswal", fp);
8. fclose(fp);
9. }
myfile.txt

This is sonoo jaiswal

C rewind() function
The rewind() function sets the file pointer at the beginning of the stream. It is useful
if you have to use stream many times.

Syntax:

1. void rewind(FILE *stream)


Example:
File: file.txt

1. this is a simple text


File: rewind.c

1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("file.txt","r");
8. while((c=fgetc(fp))!=EOF){
9. printf("%c",c);
10. }
11. rewind(fp);//moves the file pointer at beginning of the file
12. while((c=fgetc(fp))!=EOF){
13. printf("%c",c);
14. }
15. fclose(fp);
16. getch();
17. }
Output:

this is a simple textthis is a simple text


As you can see, rewind() function moves the file pointer at beginning of the file that
is why "this is simple text" is printed 2 times. If you don't call rewind() function, "this
is simple text" will be printed only once.

C ftell() function
The ftell() function returns the current file position of the specified stream. We can
use ftell() function to get the total size of a file after moving file pointer at the end of
file. We can use SEEK_END constant to move the file pointer at the end of file.

Syntax:
1. long int ftell(FILE *stream)
Example:

File: ftell.c

1. #include <stdio.h>
2. #include <conio.h>
3. void main (){
4. FILE *fp;
5. int length;
6. clrscr();
7. fp = fopen("file.txt", "r");
8. fseek(fp, 0, SEEK_END);
9. length = ftell(fp);
10. fclose(fp);
11. printf("Size of file: %d bytes", length);
12. getch();
13. }
Output:

Size of file: 21 bytes


Q>Explain COMMAND LINE ARGUMENTS IN C?

Command line arguments are the arguments specified after the program name in the
operating system's command line, and these arguments values are passed to your
program at the time of execution from your operating system. For using this concept
in your program, you have to understand the complete declaration of how the main
function works with this command-line argument to fetch values that earlier took no
arguments with it (main() without any argument).

main() accept two arguments, where the first argument denotes the number of
command line arguments whereas the second argument denotes the full list of every
command line argument.
Syntax:
int main ( int argc, char *argv [ ] ),where

 argc (ARGument Count) denotes the number of arguments to be passed and


 argv [ ] (ARGument Vector) denotes to a pointer array that is pointing to every
argument that has been passed to your program.
You must make sure that in your command line argument, argv[0] stores the name
of your program, similarly argv[1] gets the pointer to the 1st command line argument
that has been supplied by the user, and *argv[n] denotes the last argument of the
ist.
Program for Command Line Argument
Example:
#include <stdio.h>
int main( int argc, char *argv [] )
{
printf(" \n Name of my Program %s \t", argv[0]);

if( argc == 2 )
{
printf("\n Value given by user is: %s \t", argv[1]);
}
else if( argc > 2 )
{
printf("\n Many values given by users.\n");
}
else
{
printf(" \n Single value expected.\n");
}
}
Output:

You might also like