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

Week 7- Random-Access Files and Secure Programming in C

The document covers concepts related to random-access files and secure programming in C, focusing on file and stream handling, including writing and reading data using sequential and random-access methods. It emphasizes error checking for file operations to prevent unpredictable behavior and data corruption. Additionally, it provides examples of creating and manipulating random-access files, including a case study on transaction processing.

Uploaded by

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

Week 7- Random-Access Files and Secure Programming in C

The document covers concepts related to random-access files and secure programming in C, focusing on file and stream handling, including writing and reading data using sequential and random-access methods. It emphasizes error checking for file operations to prevent unpredictable behavior and data corruption. Additionally, it provides examples of creating and manipulating random-access files, including a case study on transaction processing.

Uploaded by

batam54516
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

CENG 110 – PROGRAMMING AND

COMPUTING II

Week 7 : Random-Access Files and Secure


Programming in C

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Objectives
• Understand the concepts of files and streams.
• Write data to and read data from files using sequential-
access text-file processing.
• Write data to, update data in and read data from files
using random-access file processing and binary files.
• Develop a substantial transaction-processing program.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Outline
11.5 Random-Access Files
11.6 Creating a Random-Access File
11.7 Writing Data Randomly to a Random-Access File
11.7.1 Positioning the File Position Pointer with fseek
11.7.2 Error Checking
11.8 Reading Data from a Random-Access File
11.9 Case Study: Transaction-Processing System
11.10 Secure C Programming

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.5 Random-Access Files
• Fixed-length records that may be accessed

• Appropriate for systems that require rapid access to specific data

• Every record has the same length so each record’s exact location relative to
the beginning of the file can be calculated as a function of the record key
• The following diagram shows one way to implement a random-access file

• Data can be inserted, updated or deleted without rewriting the entire file.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.6 Creating a Random-Access File
• Function fwrite writes a specified number of bytes from a specified
location in memory to a file at the file position pointer’s current location
• Function fread reads a specified number of bytes from the file position
pointer’s current location to a specified area in memory.
• Although fread and fwrite read and write data in fixed-size rather than
variable-size format, they process data as “raw” bytes
• The “raw” data representation is system-dependent, so “raw” data may not
be readable on other systems, or by programs produced by other compilers
or with different compilation options.
• fwrite and fread Can Write and Read Arrays
– The third argument of fwrite and fread is the number of elements to
process

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.7 Writing Data Randomly to a
Random-Access File
• fseek sets the file position pointer to a specific byte
position
• fwrite writes the data there.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.7.1 Positioning the File Position
Pointer with fseek (1 of 2)
• fseek(cfPtr, (client.account - 1) *
sizeof(struct clientData), SEEK_SET);
• Positions the file position pointer for the file referenced by
cfPtr to the byte location calculated by
– (client.account - 1) * sizeof(struct
clientData)
– This expression’s value is the offset or displacement
– The symbolic constant SEEK_SET indicates that fseek
should move the file position pointer relative to the
beginning of the file

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.7.1 Positioning the File Position
Pointer with fseek (2 of 2)
• Fseek’s last argument can
– SEEK_SET indicates that the seek is measured from
the beginning of the file.
– SEEK_CUR indicates that the seek is measured from
the current location in the file.
– SEEK_END indicates that the seek is measured from
the end of the file.
• Use only positive offsets with SEEK_SET and only
negative ones with SEEK_END

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.7.2 Error Checking
• For simplicity, our programs do not perform error checking
• Industrial-strength programs should determine whether fscanf,
fseek and fwrite operate correctly by checking their return values
– Function fscanf returns the number of data items successfully
read or the value EOF if a problem occurs while reading data.
– Function fseek returns a nonzero value if the seek operation
cannot be performed (e.g., attempting to seek to a position
before the start of the file)
– Function fwrite returns the number of items it successfully
output. If this number is less than the third argument in the
function call, then a write error occurred.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.7.2 Error Checking
File operations may fail due to various reasons such as:
• File not existing.
• Disk full or write-protected.
• File corrupted.
• Invalid seek positions.
• Hardware failures.
• Without error checking, your program will proceed as if everything
went fine, leading to unpredictable behavior and data corruption.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.7.2 Error Checking
• Proper Ways to Check File Operations:
• 1. Checking fscanf
• Return value: Number of items successfully read.
• If it returns EOF, there was an error (e.g., end of file or reading
problem).
• Example:
• if (fscanf(fp, "%d %s", &num, str) != 2) {
• printf("Error reading data!\n");
• // Handle error or exit
• }

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.7.2 Error Checking
• 2. Checking fseek
• Return value: 0 if successful, non-zero if failed.
• Example:

• if (fseek(fp, position, SEEK_SET) != 0) {


• printf("Error seeking in file!\n");
• // Handle error or exit
• }

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.7.2 Error Checking
• 3. Checking fwrite
• Return value: Number of items successfully written.
• Should match the number of items expected to write (usually 1 if
writing a single struct).
• Example:
• if (fwrite(&client, sizeof(struct clientData), 1, fp) != 1) {
• printf("Error writing to file!\n");
• // Handle error or exit
• }

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.7.2 Error Checking
• 4. Checking fread (Similar to fwrite)
• Return value: Number of items read.
• Should check if it matches number of items expected (usually 1).
• Example:
• if (fread(&client, sizeof(struct clientData), 1, fp) != 1) {
• printf("Error reading from file!\n");
• // Handle error, possibly EOF or other issues
• }

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.7.2 Error Checking
• Sample Rewrite Example with Error Checking:
• Example for Writing Record:
• // Move to correct position
• if (fseek(fp, (accountNum - 1) * sizeof(struct clientData), SEEK_SET)
!= 0) {
• printf("Error seeking to the record location.\n");
• return;
• }

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.7.2 Error Checking
• // Attempt to write
• if (fwrite(&client, sizeof(struct clientData), 1, fp) != 1) {
• printf("Error writing record to file.\n");
• return;
• }

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.7.2 Error Checking
• Example for Reading Record:
• if (fseek(fp, (accountNum - 1) * sizeof(struct clientData), SEEK_SET)
!= 0) {
• printf("Error seeking to record.\n");
• return;
• }
• if (fread(&client, sizeof(struct clientData), 1, fp) != 1) {
• printf("Error reading record.\n");
• return;
• }

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.7.2 Error Checking
Function Success Return Failure Return What to Check
Value Value

Fscanf Number of items EOF Did it read all


read expected items?

fseek 0 Non-zero Did seek succeed?

fwrite Number of items Less than Did it write


written expected everything?

fread Number of items Less than Did it read


read expected or 0 everything?

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.8 Reading Data from a Random-
Access File
• Function fread reads a specified number of bytes from a file into
memory
• fread(&client, sizeof(struct clientData), 1, cfPtr);
– reads the number of bytes determined by sizeof(struct
clientData) from the file referenced by cfPtr, stores the data
in client and returns the number of bytes read. It reads bytes
from the location specified by the file position pointer.
• fread can read several fixed-size array elements by providing a
pointer to the array in which the elements will be stored and by
indicating the number of elements to be read
• fread returns the number of items it successfully input. If this number
is less than the function call’s third argument, a read error occurred

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.8 Reading Data from a Random-Access File
• // Fig. 11.10: fig11_10.c Creating a random-access file sequentially

• #include <stdio.h>

• struct clientData {// clientData structure definition

• unsigned int acctNum; // account number

• char lastName[15]; // account last name

• char firstName[10]; // account first name

• double balance; // account balance

• };

• int main(void)

• { FILE *cfPtr; // accounts.dat file pointer

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.8 Reading Data from a Random-Access File
• if ((cfPtr = fopen("accounts.dat", "wb")) == NULL) {

• // fopen opens the file; exits if file cannot be opened

• puts("File could not be opened.");

• }

• else { // create clientData with default information

• struct clientData blankClient = {0, "", "", 0.0};

• // output 100 blank records to file

• for (unsigned int i = 1; i <= 100; ++i) {

• fwrite(&blankClient, sizeof(struct clientData), 1, cfPtr);

• }

• fclose (cfPtr); // fclose closes the file

• }

• }

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.8 Reading Data from a Random-Access File
• // Writing data randomly to a random-access file

• #include <stdio.h>

• // clientData structure definition

• struct clientData {

• unsigned int acctNum; // account number

• char lastName[15]; // account last name

• char firstName[10]; // account first name

• double balance; // account balance

• };

• int main(void)

• {

• FILE *cfPtr; // accounts.dat file pointer

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.8 Reading Data from a Random-Access File
• // fopen opens the file; exits if file cannot be opened

• if ((cfPtr = fopen("accounts.dat", "rb+")) == NULL) {

• puts("File could not be opened.");

• }

• else {

• // create clientData with default information

• struct clientData client = {0, "", "", 0.0};

• // require user to specify account number

• printf("%s", "Enter account number"

• " (1 to 100, 0 to end input): ");

• scanf("%d", &client.acctNum);

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.8 Reading Data from a Random-Access File
• // user enters information, which is copied into file

• while (client.acctNum != 0) {

• // user enters last name, first name and balance

• printf("%s", "Enter lastname, firstname, balance: ");

• // set record lastName, firstName and balance value

• fscanf(stdin, "%14s%9s%lf", client.lastName,

• client.firstName, &client.balance);

• // seek position in file to user-specified record

• fseek(cfPtr, (client.acctNum - 1) *

• sizeof(struct clientData), SEEK_SET);

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


11.8 Reading Data from a Random-Access File
• // write user-specified information in file

• fwrite(&client, sizeof(struct clientData), 1, cfPtr);

• // enable user to input another account number

• printf("%s", "Enter account number: ");

• scanf("%d", &client.acctNum);

• }

• fclose(cfPtr); // fclose closes the file

• }

• }

Copyright © 2022 Pearson Education, Inc. All Rights Reserved

You might also like