Computer for SEE and NEB

It is a complete SEE and NEB solution for computer science. It includes Computer Fundamentals, Database (SQL), Programming in C QBASIC, CSS, JavaScript, and PHP for beginners.

Breaking

Post Top Ad

Your Ad Spot

Thursday, October 6, 2022

Concept of File Handling in C Programming

Concept of File Handling in C Programming


Concept of File Handling in C Programming

Introduction:

File handling is an essential aspect of programming, and it involves reading from and writing to files. In C programming, file handling is achieved through a set of standard library functions that allow for file manipulation. These functions provide the programmer with the ability to read, write, and modify files. In this blog post, we will explore the concept of file handling in C programming and how it is used to manipulate files.

Concept of Data File

As we know, while the program is processing the content of the variable that within stored in RAM but the problem is if such values of the variable are needed in the future, then this causes the problem because the value of the variable is only within the program is being processed. After a program is over, the content of the RAM is gets erased. To overcome this problem, we can use a file to save the content into it, so that we can retrieve content from the data file whenever we want to it.

 



Binary files and Text files

Binary files and text files are supported by C programming.

In text files, everything is stored in terms of text i.e. even if we store an integer 54,  it will be stored as a 3-byte string- “54\0”. In a text file certain character translations may occur. For example a newline (\n) character may be converted to a carriage return.

To access any file, we need to declare a pointer to FILE structure and then associate it with particular file. Pointer is used to declare the file fainter.

FILE  *fp;

 

 Sequential and Random File

1. Sequential File Processing:

In this technique, the content is stored sequentially and read back the content sequentially in a normal way using a loop and some functions using rewind(), ftell(), etc.

2. Random File Processing: 

In this technique, the data are read randomly.

a) fseek() :-The function fseek() is used to set the file position.

Its syntax is:

int fseek(FILE   *fp, long offset, int pos);

The first argument is the pointer to a file.
 

b) ftell() :- This function returns the current position of the file position pointer.
Its syntax is:
long  ftell(FILE   *fp);                      

 

c)  rewind() :- This function is used to move the file position pointer to the beginning of the file. This function is useful when we open a file for update.
Its syntax is:
rewind(FILE  *fp);

 

File operations
There are following file operations
a) Creation of a new file
b) Opening an existing file
c) Reading from a file
d) Writing a file
e) Moving to a file in a specific location
f) Closing a file


File manipulation function

Character I/O

fputc( )

Declaration :

 int fputc( int c, FILE *fptr);         

This function writes a character to the specified file at the current file position and then increments the file pointer position.

 

fgetc( )
Declaration :
 int fgetc(FILE *fptr);     
It is used to read the single character form the file.

 

getc( ) and putc( )

The operations of getc( ) and putc( ) are exactly similar to that of fgetc( ) and fputc( ), the only difference is that the former two are defined as macros.

Integer I/O

putw( )

Declaration:

int putw(int value, FILE *fptr)    

This function writes an integer value to the file pointed to by fptr.

 

getw( )

Declaration :

int getw(FILE *fptr);      

This function returns the integer value from the file associated with fptr.


String I/O

fputs( )

Declaration:  

int fputs(const char *str, FILE *fptr);      

It means file put string. It writes the string for output.

 

fgets( )

Declaration:   

char *fgets(char *str, int n, FILE *fptr);      

This function is used to read characters from a file and these characters are stored in the string pointed by str.

 

Formatted I/O

fprintf( )

Declaration:  

fprintf( FILE *fptr, const char *format[arguments]);       

This function is same as the printf( ) function but it stores the data in data file.

 

fscanf( )

Declaration:  

fscanf( FILE *fptr, const char *format[address]); 
             
It works as a same as a scanf( ) function but it reads data from a the file instead the of standard input device, so it has one more parameter which is a pointer of FILE type and it points to the file from which data will be read.

 

Block I/O

fwrite( )

Declaration:

size_t fwrite(const void *ptr,size_t size,size_t n,FILE *fptr);       

It is used for writing an entire line.

 

fread( )

Declaration:

size_t fread(void *ptr, size_t size, size_t n, FILE *fptr); 

It is used to read an entire given file.

 

Renaming and deleting file

Function remove( ) is used to delete the file whose syntax is as follows:

remove(filename);        

 

Function rename( ) is used to rename old file name into new file name. Its syntax is as follows:

rename(old_file_name,new_file_name);

 

Opening, Reading, Writing and Appending data file

 

Opening a file

A file must be opened before any input/output operations performed on that file.

Syntax:

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

fopen() function takes two strings as arguments, the first one is the name of the file to be opened and the second one is the mode that decides which operations are to be performed on the file.

FILE   *fp1,fp2;

fpl = fopen(“myfile.txt”,“w”);

fp2 = fopen(“yourfile.dat”,“r”);

 

 

Modes in file handling

The possible values of mode are-

"w” (write)

If the file doesn’t exist then this mode creates a new file for writing, and if the file already exists then the previous data is erased and new data entered is written to the file.


“a” (append)

Open an existing text file for appending.


“r” (read)

Open an existing file for read only.


“w+” (write + read)

Open a new file for reading and writing. In case of existing file, it will destroy, and new file will be created.


“r+” (read + write)

It Open an existing file for both reading and writing purpose.


“a+” (append + read)

It Opens an existing data file for reading and appending.

 

 Reading from a file

We can use fscanf() and fgets() functions to read the file.

Syntax:

fscanf(<file pointer>, <”format specifier”>,< variable>);

fscanf(filePointer, "%s %s  %d", str1, str2,, &yr);

Example: 1

File reading using scanf.

#include<stdio.h>

#include<conio.h>

void main()

{

clrscr();

FILE *fptr;

char str[100];

fptr=fopen("AVN.TXT","r");

printf("%d\n",fptr);

do

{

fscanf(fptr,"%s",str);

printf("%s ",str);

}

while(!feof(fptr));

fclose(fptr);

getch();

}

 

Example:  2

File Reading using  fgetc

#include <stdio.h>

int main()

{

  char ch;

  FILE *fp;

  fp = fopen("abc.txt", "w+");

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

  {

    printf("%c", ch);

  }

  fclose(fp);

 

  return 9;

}

 

Example 3:

File Reading using fgets.

#include <stdio.h>

int main()

{

  char str[80];

  FILE *fp;

  fp = fopen("abc.txt", "w+");

  while( (fgets(str, 79, fp)) != NULL )

  {

    printf("%s", str);

  }

  fclose(fp);

 

  return 0;

}

 

 

 

Writing a file

In writing file operation fprintf(), and fputs() functions are used to store the data in data file.

FILE *filePointer ;

filePointer = fopen(“fileName.txt”, “w”);

fprintf(<file pointer>, <”text to be written to file”>,….);

                                               

Example: 1

#include <stdio.h>

 int main()

{

FILE *fp;

   file = fopen("file.txt","w");       // Create a file and add text

   fprintf(fp,"%s","This is just an example");

   fclose(fp);

    return 0;

}

 

Example 2:

File Writing using fputc

#include <stdio.h>

int main()

{

  char str[]= "Welcome to file handling";

  int i=0;

  FILE *fp;

  fp = fopen("abc.txt", "a");

  while( str[i] != '\0' )

  {

    fputc(str[i], fp);

    i++;

  }

  fclose(fp);

 

  return 0;

}

 

Example 3:

File Writing using fputs  String by String

#include <stdio.h>

int main()

{

  char str[]= "RAM and Shyam ";

  FILE *fp;

  fp = fopen("abc.txt", "a");

  fputs(str, fp);

  fclose(fp);

 

  return 0;

}

 

 

File Append mode

Append mode add more data at the end f the exiting file. It cannot overwrite an existing file.

Syntax:

FILE *fopen(const char *filename, const char *mode)

OR

FILE *fp = fopen(<path>, "a");

FILE *fp = fopen(<path>, "a+");

 

Closing a File

To close the file we use fclose() function.

Syntax:

fclose(FILE *fptr);

 



Conclusion:

In conclusion, file handling is a vital aspect of programming, and it allows for the manipulation of files in C programming. The standard library functions fopen(), fclose(), fwrite(), fread(), fprintf(), fscanf(), fseek(), and ftell() provide the programmer with the ability to read from and write to files, move the file pointer, and format data to be printed or read in a specific format. By mastering the concept of file handling in C programming, programmers can create programs that read from and write to files, which is a useful skill in a wide range of applications, including data storage and retrieval, data processing, and data analysis.

You can also Read:




No comments:

Post a Comment

Post Top Ad

Your Ad Spot

Pages