Files in C Programming

Introduction

  • A collection of data which is stored on a secondary device like a hard disk is known as a file.
  • A file is generally used as real-life applications that contain a large amount of data.
There are two problems with such applications:
I) It is time-consuming and unmanageable for handling such huge amount of data,
II) When the I/O terminal is used the entire data is lost if the program is terminated or the computer is being turned off. So it is a compulsion for storing the data on a permanent device.

Files are divided into two types

1. Stream-oriented – they are standard or high-level files. They are easier to work with than the sytem-oriented data-files and are used more commonly.
2. System-oriented – they are low-level files.

The library functions which are used for operating the files are:

1. High-level file I/O functions – they do their own buffer management.
2. Low-level file I/O functions – the buffer management is done by the programmer.

Let us go through the file operations in detail one by one.

Opening a file

Before opening any file, a file pointer needs to be established.

Syntax : Establishing a file pointer
FILE *fptr;

Where,
FILE is the structure which is defined in the header file <stdio.h>.

  • A file should be opened before any operation is being performed on it.
  • The fopen() function is being used for opening the file.
Syntax:
FILE *fopen(const char *filename, const char *mode);

In the above syntax, filename is the literal which is used for naming the files.

They can be accessed by using the following modes:

ModeDescription
“r”It opens an existing file for reading only.
“w”It opens a new file for writing. If the filename does not exist it will be created and if the file already exists then its contents are deleted.
“a”It appends the existing file. If the filename does not exist it will be created.
“r+”It opens an existing file for reading and writing. It indicates that the file is to be read before writing.
“w+”It opens a new file for reading and writing. If a file with the current filename exists then it is destroyed and a new file name is created.
“a+”It opens an existing file for reading and appending. Its stream is positioned at the end of the file content.

Closing a file

  • The fclose() function is used for closing a file.
  • When this function is used the file pointer is disconnected from a file.

  • Syntax:
    int fclose(FILE *fp);

    Where,
    fp is the file pointer that points to the file that has to be closed.

  • An integer value is returned which will indicate if the function was successful or not.
  • In addition to the fclose() function we even have the fcloseall() function which will close all the streams which are open currently except the standard streams (stdin, stdout and stderr).

  • Syntax:
    intfcloseall(void);

  • This function will flush any of the stream buffers and will return the number of streams which are closed.

Reading a file

Following are the list of functions which are used for reading a file:

FunctionsSyntaxDescription
fscanf( )int fscanf (FILE *stream, const char *format,....);It is used for reading the formatted data from the stream.
fgets( )char *fgets(char *str, int size, FILE *stream);It stands for file get string. It is used for getting the string from a stream.
fgetc( )int fgetc (FILE *stream);It will return the next character from the stream from the end of the file or an error.
fread( )int fread(void *str, size_t size, size_t num, FILE *stream);It is used for reading data from a file.

Writing a file

Following are the list of functions which are used for writing a file:

FunctionsSyntaxDescription
fprintf()int fprintf (FILE *stream, const char * format,...);It is used for writing the formatted output of the stream.
fputs()int fputs(const char *str, FILE *stream);It is used for writing a line to a file.
fputc()int fputc(int c, FILE *stream);It is opposite to fgetc() and is used for writing a character to the stream.
fwrite()int fwrite(const void *str, size_t size, size_t count, file *stream);It is used for writing data to a file.

Error handling in file operations

The function ferror() is used for checking the errors in the stream.

Syntax:
int ferror(FILE *stream);

This function returns 0 if there are no errors and a value if there are some errors.

Following are the functions which are used for detecting the errors:

FunctionsSyntaxDescription
clearerr()void clearerr(FILE *stream);It is used for clearing the end-of-file and error indicators for the stream.
perror()void perror(char *msg);It stands for the print error.

Accepting the command line arguments

The main() can accept two arguments

I) First argument will be an integer value that will specify the number of command-line arguments.
II) The second argument is a full list of all the command-line arguments.

Syntax:
int main (int arg c, char *argv[])

Where,
arg c will specify the number of arguments that are to be passed into the program from the command-line including the name of the program.

  • argv will contain the list of all the arguments.
  • Each element of the array argv is a pointer where each pointer points to a string.
  • In main() the command line arguments are accepted by using the argc and argv.

Example

Write a program for reading a file character by character and display it on the screen.

#include <stdio.h>
#include <string.h>
void main()
{
    FILE *fp;
    int c;
    char fnm[25];
    printf("\n Enter a filename:");
    scanf("%s",fnm);
    fp = fopen(fnm, "r");
    if (fp==NULL)
    {
        printf("\n Error in opening the file");
        exit(1);
    }
    c=fgetc(fp);
    while(c!=EOF)
    {
         putchar(c);
         c =fgetc(fp);
    }
    fclose(fp);
}


Output:
Assuming that we are using a text file hello.txt, that has the following content:

Welcome to TutorialRide

Now, the output is of the above problem will be:

Welcome to TutorialRide

Functions used for selecting a record randomly

Following are the functions which are used for selecting a record randomly:

FunctionsSyntaxDescription
fseek()int fseek(FILE *stream, long offset, int origin);It is used to reposition a binary stream.
ftell()long ftell (FILE *stream);It is used to know the current position of the file pointer.
rewind()void rewind (FILE *f);It is used for adjusting the position of the file pointer to the next I/O operation and it will take place at the beginning of the file.
fgetpos()int fgetpos (FILE *stream, fpos_t *pos);It is used for determining the current position of the stream.

remove()

The remove() function is used for erasing a file.

Syntax:
int remove (const char *filename);

  • All the files which are specified by the filename will be erased.
  • If this function is successful it will return a zero else it will return a value other than zero.

Example : Removing a file

#include <stdio.h>
void main()
{
     remove(“hello.txt”);
}

Renaming the file

The rename() function is used for renaming a file.

Syntax:
int rename(const char *oldname, const char *newname);

Where,
oldname will be the pathname of the file that needs to be renamed.
newname will be the new pathname of the file.

  • If this function is successful it will return a zero else it will return a value other than zero.
  • If an error occurs neither the oldfile name nor the newfile name are renamed or changed.

Example : Renaming a file

#include <stdio.h>
void main()
{
     int successful=0;
     successful = rename("hello.txt", "hey.txt");
     if (successful !=0)
     printf("\nThe file is not renamed");
}