CH 11 Deitel How To Program
CH 11 Deitel How To Program
1. Introduction
File processing allows for long-term data storage on secondary devices (e.g., hard drives,
SSDs).
Files provide a persistent way to store data compared to volatile variables.
Types of file access:
1. Sequential Access: Processed in a linear manner, record-by-record.
2. Random Access: Access any record directly, ideal for transaction processing
systems.
Opening a File:
o Use fopen(filename, mode) to open files. Common modes:
"r": Open for reading.
"w": Open for writing (creates file or overwrites existing content).
"a": Append mode (writes to the end of the file).
"r+", "w+", "a+": Read/write combinations.
Closing a File:
o Always close files with fclose() to ensure data integrity and release system
resources.
Error Handling:
o fopen() returns NULL if file opening fails. Always check the return value of file
functions.
4. Sequential-Access Files
c
Copy code
fprintf(filePtr, "%d %s %.2f\n", id, name, balance);
Reading Data:
o Use fscanf() to read formatted data.
o Example:
c
Copy code
fscanf(filePtr, "%d%s%f", &id, name, &balance);
Limitations:
o Modifying records is challenging due to varying record lengths; rewriting the file
is often required.
5. Random-Access Files
Definition: Use fixed-length records to enable direct access without traversing previous
records.
Advantages:
o Insert, update, or delete records without rewriting the entire file.
o Ideal for systems requiring fast access, such as banking or reservation systems.
Key Functions:
o fseek(FILE *stream, long offset, int origin):
Moves the file pointer to a specific byte position.
origin values: SEEK_SET (beginning), SEEK_CUR (current), SEEK_END
(end).
o fwrite() and fread():
fwrite() writes fixed-size records.
fread() reads fixed-size records.
c
Copy code
struct Record { int id; char name[20]; float balance; };
FILE *fp = fopen("data.dat", "wb+");
// Write a record
struct Record rec = {1, "Alice", 100.5};
fwrite(&rec, sizeof(rec), 1, fp);
// Read a record
fseek(fp, 0, SEEK_SET);
fread(&rec, sizeof(rec), 1, fp);
fclose(fp);
The file position pointer determines where the next read/write occurs.
Use rewind(FILE *stream) to reset the pointer to the beginning of the file.
Practical Questions
14. Write a program snippet to open a file for writing and store a string in it.
15. How can you read a record from a random-access file? Provide an example.
16. Write a program to create a sequential file that stores student IDs and grades.
17. Use fseek to move the file pointer to the third record in a random-access file.
18. Demonstrate how to use fwrite to write a structure to a binary file.
19. Why should you check the return value of fopen, fwrite, and fread?
20. What precautions should be taken to avoid overwriting existing data?