***Welcome to ashrafedu.blogspot.com * * * This website is maintained by ASHRAF***

Posts

    Friday, September 10, 2021

    File Organization

    There are two types of files- sequential file and random access file. In sequential file, data are kept sequential. As example if we want to access the forty fourth record, then first forty three records should be read sequentially to reach the forty fourth record. In the record access file, the data can be accessed and processed randomly i.e in this case the forty fourth record can be accessed directly. It takes less time than the sequential file.

    Hence depending up on the method of accessing the data stored , there are two types of files.

    1. Sequential file
    2. Random access file

    1.Sequential File: In this type of files data is kept in sequential order if we want to read the last record of the file, we need to read all records before that record so it takes more time.

    sequential file is a sequence of records. The records may or may not be kept in sorted order in the sequence. In standard C input/output all files are sequential files.

    Sequential Access to a data files means that the computer system reads or writes information to the file sequentially, starting from the beginning of the file and proceeding step by step.

    2.Random access Files: In this type of files data can be read and modified randomly .If we want to read the last record we can read it directly. It takes less time when compared to sequential file.

    Random Access to a file means that the computer system can read or write information anywhere in the data file. This type of operation is also called “Direct Access” because the computer system knows where the data is stored and hence goes “directly” and reads the data.

     

    File Management functions

    A File can be used to store a large volume of persistent data. Like many other languages ‘C’ provides following file management functions,

    1. Creation of a file
    2. Opening a file
    3. Reading a file
    4. Writing to a file
    5. Closing a file

    Creating and Opening Files

    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 );

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

    Functions

    Syntax

    Description

    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.


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

    Functions

    Syntax

    Description

    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.


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

    Functions

    Syntax

    Description

    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.


    Closing a file :

    After every successful file operation, always close a file.

    For closing a file, fclose function is used.

    Ex:

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

    ---------- Some file Operations -------

    fclose(filePointer)


    Working with Binary files

    Binary files are very similar to arrays except for the fact that arrays are temporary storage in the memory but binary files are permanent storage in the disks.

    The most important difference between binary files and a text file is that in a binary file, you can seekwrite, or read from any position inside the file and insert structures directly into the files.

    The reasons why binary files are necessary:

    1. I/O operations are much faster with binary data.

    Usually, large text files contain millions of numbers. It takes a lot of time to convert 32-bit integers to readable characters. This conversion is not required in the case of binary files as data can be directly stored in the form of bits.

    2. Binary files are much smaller in size than text files.

    For data that is in the form of images, audio or video, this is very important. Small size means less storage space and faster transmission. For example, a storage device can store a large amount of binary data as compared to data in character format.

    3. Some data cannot be converted to character formats.

    The basic parameters that the read and write functions of binary files accept are:

    • the memory address of the value to be written or read
    • the number of bytes to read per block
    • the total number of blocks to read
    • the file pointer

    The functions provided by C libraries are to seekread, and write to binary files.

    The fread() function is used to read a specific number of bytes from the file. An example of fread() looks like this:

    fread(&myRecord, sizeof(struct record), 1, ptr);


    This statement reads 'a' bytes (in this case, it's the size of the structure) from the file into the memory address &myRecord. Here the number 1 denotes the number of blocks of 'a' bytes to be read. If we change it to 10, then it denotes 10 blocks of 'a' bytes will be read and stored into &myRecordptr is the pointer to the location of the file that is being read.

    Now the fwrite() function is used to write to a binary file, like so:

    fwrite(&myRecord, sizeof(struct record), 1, ptr);

    Getting data using fseek()

    If you have many records inside a file and need to access a record at a specific position, you need to loop through all the records before it to get the record.

    This will waste a lot of memory and operation time. An easier way to get to the required data can be achieved using fseek().

    As the name suggests, fseek() seeks the cursor to the given record in the file.

    Syntax of fseek():

    fseek(FILE * stream, long int offset, int whence);

    The first parameter stream is the pointer to the file. The second parameter is the position of the record to be found, and the third parameter specifies the location where the offset starts.

    example:

    fseek(fptr, -sizeof(struct threeNum), SEEK_END);


    FILES in C

    A file represents a sequence of bytes, regardless of it being a text file or a binary file.

    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. 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.

    C programming language provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices.

    A text file is a collection of characters. Binary file is a collection of bytes.

    USING FILES IN C

    To use a file four essential actions should to be carried out.

    These are :

    ·         Declare a file pointer variable.

    ·         Open a file using the fopen() function.

    ·         Process the file using suitable functions.

    ·         Close the file using the fclose() function.

    Declaration of File Pointer

    Files may be used in a program, when reading or writing, the type of file that is to be used must be specified. This is accomplished by using a variable called a file pointer, a pointer variable that points to a structure FILE. FILE is a structure declared in stdio.h. The members of the FILE structure are used by the program in various file access operations.

    File pointer is used which is declared as

    FILE  *filePointer;

    Opening Files

    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 );

    filename is a string literal, which is used  to name file, and access mode can have one of the following values –

    • “r” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen( ) returns NULL.
    • “w” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.
    • “a” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.
    • “r+” – Searches file. If is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file.
    • “w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new file is created. Returns NULL, if unable to open file.
    • “a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.
    • “rb” - Open a binary file for reading
    • “wb” - Open a binary file for writing
    • “ab” - Append to a binary file
    • “r+b” - Open a binary fi le for read/write
    • “w+b” - Create a binary file for read/write
    • “a+b” - Append a binary file for read/write

    If File pointer is used which is declared as

    FILE  *filePointer;

    So, the file can be opened as

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

    Reading from a file –

    The file read operations can be performed using functions fscanf or fgets. Both the functions performed the same operations as that of scanf and gets but with an additional parameter, the file pointer. So, it depends on how to read the file - line by line or character by character.

    Ex:

    FILE * filePointer;

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

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

    Writing a file –

    The file write operations can be perfomed by the functions fprintf and fputs with similarities to read operations.

    Ex:

    FILE *filePointer ;

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

    fprintf(filePointer, "%s %s %s %d", "We", "are", "in", 2012);

    Closing a file –

    After every successful file operation, always close a file.

    For closing a file, fclose function is used.

    Ex:

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

    ---------- Some file Operations -------

    fclose(filePointer)

     



    Top