Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Login

Register Now

Welcome to All Test Answers

Lab – 8 File Processing – Sequential and Direct Access

60-141 – Introduction to Programming II
Objective: In this Lab you will practice using sequential and direct access forms of writing and reading to and from a text (character based) file and a binary file.
PRELIMINARY NOTE:
There are two basic types of file processing, one involving character (or text) based data where the records are of variable length, in general. The other kind of file contains records that are of fixed length and the types of data may be both character and machine (binary) representations. This lab is divided into two parts. When you are finished, you should be able to clearly distinguish the type of file and the different functions required to access records in each kind of file, as well as other aspects of files.
PART 1: Sequential Files
Background:
To process sequential text files in C, we use the header file where various functions for file processing are defined. A few of them are:
1. fopen (): to open a file,
2. fclose (): to close a file,
3. fscanf (): to read from a file, and
4. fprintf (): to write into a file.
Work to do:
PART – 1A
Writing into a Sequential File:
In this lab you will be using the structure (as defined below) and implement an interactive program capable of prompting the user and storing 3 employee records into a file called “employee.dat”. Write a program called “Lab8a.c” that creates the file called “employee.dat”. This “employee.dat” file will also be used in the second part of this laboratory exercise.
The format of the file would look like this sample (excluding the first line):
ID FIRSTNAME LASTNAME
10 john doe 64.5
20 mary jane 92.3
40 alice bower 54.0
30 jim smith 78.2
Instructions: Write a C program called “Lab8a.c” to accomplish the following: (The skeleton code is given below for your convenience. Use the 3 functions specified to perform the input, printing and saving the records to the file.)

#include <stdio.h>
struct employee {
char firstname[40];
char lastname[40];
int id;
int GPA;
};
typedef struct employee Employee;
/* Input the employee data interactively from the keyboard */
void InputEmpRecord(Employee *EmpList);
/* Display the contents of Employee records from the list */
void PrintEmpList(const Employee *EmpList);
/* Save the employee records from the list to the newly created text
file specified by FileName */
void SaveEmpList(const Employee *EmpList, const char *FileName);
int main() {
Employee EmpList[3];
InputEmpRecord(EmpList);
PrintEmpList(EmpList);
SaveEmpList(EmpList, "employee.dat");
return 0;
}
}

PART – 1B
Reading from a Sequential File:
Write a different C program called “Lab8b.c” that reads the file “employee.dat” (from Part A above)
containing the 3 records created in part A into an array called EmployeeList (of type employee, size 3).
Then, write and use the WordCap(char *word) function to capitalize only the first letter of each of the
first and last names of the 3 employee records. Then save the new records back to the “employee.dat”
file, overwriting the old records.
Note: After you run program “Lab8b.c” you can use the command “cat employee.dat” to view the
contents of the file and verify the results – you can also use a standard editor. The file now should look
like this sample (excluding the first line):
ID FIRSTNAME LASTNAME
10 John Doe 64.5
20 Mary Jane 92.3
40 Alice Bower 54.0
30 Jim Smith 78.2
PART 2: Direct Access (Binary) Files
Background:.
To process direct access binary files in C, we use the header file where various functions for
file processing are defined. A few of them are:
1. fopen (): to open a file,
2. fclose (): to close a file,
3. fread (): to read from a file, and
4. fwrite (): to write into a file.
5. fseek (): position the read-write head to a desired location for I/O
Work to do:
PART – 2A
Writing into a Direct Access File:
In this lab you will be using the structure (as defined below) and implement an interactive program
capable of prompting the user and storing 3 employee records into a file called “employeeDA.dat”
(DA is shorthand for Direct Access). Write a program called “Lab8c.c” that creates the file called
“employeeDA.dat”. This file will also be used in the 2B part of this exercise. Note that the input can
come directly from the file “employee.dat” created in Part 1B.
The format of the file would look like this sample (excluding the first line):
ID FIRSTNAME LASTNAME GPA
10 John Doe 64.5
20 Mary Jane 92.3
40 Alice Bower 54.0
30 Jim Smith 78.2
Instructions: Write a C program called “Lab8c.c” to accomplish the following: (The skeleton code is
given below for your convenience. Use the 3 functions specified to perform the input, printing and
saving the records to the file.)

#include <stdio.h>
struct employee {
char firstname[40];
char lastname[40];
int id;
float GPA;
};
typedef struct employee Employee;
/* Input the employee data interactively from the keyboard */
void InputEmpRecord(Employee *EmpList);
/* Display the contents of Employee records from the list */
void PrintEmpList(const Employee *EmpList);
/* Save the employee records from the list to the newly created
binary file specified by FileName */
void SaveEmpList(const Employee *EmpList, const char *FileName);
int main() {
Employee EmpList[4];
InputEmpRecord(EmpList);
PrintEmpList(EmpList);
SaveEmpList(EmpList, "employee.dat");
return 0;
}

Note that the function SaveEmpList() must perform opening of the file “employee.dat” for writing in
binary mode, then writing all records, and finally closing the file. Make sure that the character arrays
used for first and last name are fully initialized (e.g. use ‘\0’) before writing to file (to ensure that all
data fields hold initial data).
PART – 2B
Reading and modifying data from a Direct Access File:
Write a different C program called “Lab8d.c” that performs an in-place sort by GPA of the data in
“employee.dat”. This means that the records in the file must be re-arranged, or sorted, using the GPA
as the sorting key value. You may not use an array to hold all file data. You may only store records in
at most two data structures within your program. The records must be in order from highest to lowest
GPA. To prove if your program works, start by reading in each record and then outputting the
information to the monitor (stdout) until encountering end-of-file; during this process you can
determine the number of records in the file. After closing and re-opening the file, perform a sort in
much the same way that one sorts elements of an array – if two adjacent records are not in the correct
order, then swap them. Use a temporary structure to swap records. You may use any algorithm for
sorting. Finally, after the sort is finished, once again output all records to show that they appear in
sorted order.
Note: Students should examine the content of the file “employee.dat” to verify that not all information
in each record is human-readable as characters/digits/punctuation.
Using the data given above, the final sorted file output should look like:
ID FIRSTNAME LASTNAME GPA
20 Mary Jane 92.3
30 Jim Smith 78.2
10 John Doe 64.5
40 Alice Bower 54.0
Summary of the lab requirements: There are two parts to this lab exercise – for maximum
benefit you must do both parts. You must write two programs for each part of this lab, namely
Lab8a.c and Lab8b.c (for Part 1 on sequential files) and Lab8c.c and Lab8d.c (for Part 2 on
direct access files). Be prepared to demonstrate both programs with appropriate test input
examples (including the example data provided).
At first it may seem that there is great deal of work in this lab. However, after thinking
carefully, you should realize that with only a few changes (mostly to I/O functions), the second
set of programs are similar to the first set and time and effort can be saved by careful re-use
of code.

Answer:

Part A

#include<stdio.h>
#include<stdlib.h>

struct employee{
    char firstName[40];
    char lastName[40];
    int ID;
};

typedef struct employee Employee;

void InputEmpRecord(Employee *EmpList);
void PrintEmpList(const Employee *EmpList);
void SaveEmpList(const Employee *EmpList, const char *FileName);

#define SIZE 3
int main() {

    Employee EmpList[SIZE];

    InputEmpRecord(EmpList);
    PrintEmpList(EmpList);
    SaveEmpList(EmpList, "employee.dat");

    return 0;
}

/* Input the employee data interactively from the keyboard */
void InputEmpRecord(Employee *EmpList)
{
    int i;
    for(i=0; i<SIZE; i++)
    {
        printf("Enter data for employee 1:\n", i+1);
        printf("ID? ");
        scanf("%d", &EmpList[i].ID);
        printf("First Name? ");
        scanf(" %s", EmpList[i].firstName);
        printf("Last Name? ");
        scanf(" %s", EmpList[i].lastName);
    }
}

/* Display the contents of a given Employee record */
void PrintEmpList(const Employee *EmpList)
{
    int i;

    printf("ID\tFirstName\tLastName\n");
    for(i=0; i<SIZE; i++)
    {
        printf("%d\t%s\t\t%s\n", EmpList[i].ID, EmpList[i].firstName, EmpList[i].lastName);
    }
}

/* Save (append) the employee record to the text file
   specified by FileName (one record at a time) */
void SaveEmpList(const Employee *EmpList, const char *FileName)
{
    FILE *fp;
    int i;
    if((fp = fopen(FileName, "w")) == NULL)
    {
        printf("File opening error\n");
        exit(0);
    }
    fprintf(fp, "ID\tFirstName\t\tLastName\n");
    for(i=0; i<SIZE; i++)
    {
        fprintf(fp, "%d\t%s\t\t%s\n", EmpList[i].ID, EmpList[i].firstName, EmpList[i].lastName);
    }
    fclose(fp);
}

Part B

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct employee{
    char firstName[40];
    char lastName[40];
    int ID;
};

typedef struct employee Employee;

char *CapWord(char *word);
void ReadEmpList(Employee *EmpList, const char *FileName);
void PrintEmpList(const Employee *EmpList);
void SaveEmpList(const Employee *EmpList, const char *FileName);

#define SIZE 3
int main() {

    Employee EmpList[SIZE];
	int i;

    ReadEmpList(EmpList, "employee.dat");

    for(i = 0; i < SIZE; i++)
    {
		strcpy(EmpList[i].firstName, CapWord(EmpList[i].firstName));
		strcpy(EmpList[i].lastName, CapWord(EmpList[i].lastName));
	}

	PrintEmpList(EmpList);
    SaveEmpList(EmpList, "employee.dat");

    return 0;
}

/* Read the employee data from the file */
void ReadEmpList(Employee *EmpList, const char *FileName)
{
    FILE *fp;
    int i;
    char temp[40];
    if((fp = fopen(FileName, "r")) == NULL)
    {
        printf("File opening error\n");
        exit(0);
    }
    fscanf(fp, " %s %s %s", temp, temp, temp);

    for(i=0; i<SIZE; i++)
    {
        fscanf(fp, " %d %s %s", &EmpList[i].ID, EmpList[i].firstName, EmpList[i].lastName);
    }
    fclose(fp);
}

/* Convert the first letter of a word to capital */
char *CapWord(char *word)
{
	word[0] = toupper(word[0]);
	return word;
}

/* Save (append) the employee record to the text file
   specified by FileName (one record at a time) */
void SaveEmpList(const Employee *EmpList, const char *FileName)
{
    FILE *fp;
    int i;
    if((fp = fopen(FileName, "w")) == NULL)
    {
        printf("File opening error\n");
        exit(0);
    }
    fprintf(fp, "ID\tFirstName\t\tLastName\n");
    for(i=0; i<SIZE; i++)
    {
        fprintf(fp, "%d\t%s\t\t%s\n", EmpList[i].ID, EmpList[i].firstName, EmpList[i].lastName);
    }
    fclose(fp);
}

/* Display the contents of a given Employee record */
void PrintEmpList(const Employee *EmpList)
{
    int i;

    printf("ID\tFirstName\tLastName\n");
    for(i=0; i<SIZE; i++)
    {
        printf("%d\t%s\t\t%s\n", EmpList[i].ID, EmpList[i].firstName, EmpList[i].lastName);
    }
}

About

Leave a reply

Captcha Click on image to update the captcha .

error: Content is protected !!