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

Introduction To Programming (C/C++) : Chapter 9: File Handling

This chapter discusses file handling in C/C++ programming. It covers sequential access files, which are read from beginning to end, and random access files, which allow direct access to records without reading through other records. The key points are: 1) Sequential access files are created using functions like fopen() and data is read with fscanf(). Random access files store fixed-length records and allow direct access using fseek() and fread()/fwrite(). 2) Common file I/O functions include fopen(), fclose(), fread(), fwrite(), fseek(), fgetc(), fputc(), fgets(), fputs(), fscanf(), fprintf() for reading from and writing

Uploaded by

Pháp Lê
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Introduction To Programming (C/C++) : Chapter 9: File Handling

This chapter discusses file handling in C/C++ programming. It covers sequential access files, which are read from beginning to end, and random access files, which allow direct access to records without reading through other records. The key points are: 1) Sequential access files are created using functions like fopen() and data is read with fscanf(). Random access files store fixed-length records and allow direct access using fseek() and fread()/fwrite(). 2) Common file I/O functions include fopen(), fclose(), fread(), fwrite(), fseek(), fgetc(), fputc(), fgets(), fputs(), fscanf(), fprintf() for reading from and writing

Uploaded by

Pháp Lê
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Introduction to

Programming (C/C++)

Chapter 9: File Handling

Nguyen Le Hoang Dung


[email protected]
Objectives

In this chapter, you will learn:


• Files and Streams
• Creating a sequential access file
• Reading data from a sequential access file
• Updating sequential access files

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 2


Objectives (continued)

In this chapter, you will:


• Random Access Files
• Creating a random access file
• Writing data randomly to a random access file
• Reading data sequentially from a random
access file

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 3


Introduction

• Data files
− Can be created, updated, and processed by C
programs
− Are used for permanent storage of large
amounts of data
• Storage of data in variables and arrays is only
temporary

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 4


The Data Hierarchy
Hierarchy of data Example
001 - Nguyen Van A – 227 Nguyen Van Cu
Files
002 – Dam Thi B – 223B Nguyen Van Cu

Records 001 - Nguyen Van A – 227 Nguyen Van Cu

Fields Nguyen Van A

Characters (byte) 1001110 (letter N in ASCII)

Bit 1 Or 0

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 5


Files and Streams

• C views each file as a sequence of bytes


− File ends with the end-of-file marker
• Or, file ends at a specified byte
• Stream created when a file is opened
− Provide communication channel between files and
programs
− Opening a file returns a pointer to a FILE
structure
• Example file pointers:
• stdin - standard input (keyboard)
• stdout - standard output (screen)
• stderr - standard error (screen)
Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 6
Files and Streams (continued)
• Read/Write functions in standard library
− fgetc
• Reads one character from a file
• Takes a FILE pointer as an argument
• fgetc( stdin ) equivalent to getchar()
− fputc
• Writes one character to a file
• Takes a FILE pointer and a character to write
as an argument
• fputc( 'a', stdout ) equivalent to
putchar( 'a' )

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 7


Files and Streams (continued)
• Read/Write functions in standard library
− fgets
• Reads a line from a file
− fputs
• Writes a line to a file
− fscanf / fprintf
• File processing equivalents of scanf
and printf

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 8


Creating a Sequential Access File

• Creating a File
− FILE *myPtr;
• Creates a FILE pointer called myPtr
− myPtr = fopen("myFile.dat",
openmode);
• Function fopen returns a FILE pointer
to file specified
• Takes two arguments – file to open and
file open mode
• If open fails, NULL returned
Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 9
Creating a Sequential Access File
(continued)
− feof( FILE pointer )
• Returns true if end-of-file indicator (no
more data to process) is set for the
specified file
− fclose( FILE pointer )/fcloseall()
• Closes specified file
• Performed automatically when program
ends
• Good practice to close files explicitly
Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 10
Creating a Sequential Access File
(continued)
Mode Description
r Open a file for reading.
Create a file for writing. If the file already
w
exists, discard the current contents.
Append; open or create a file for writing at end
a
of file.
r+ Open a file for update (reading and writing).
Create a file for update. If the file already
w+
exists, discard the current contents.
Append; open or create a file for update;
a+
writing is done at the end of the file.
Table of file open modes
Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 11
Reading Data from a Sequential
Access File
• Reading a sequential access file
− Create a FILE pointer, link it to the file to
read
myPtr = fopen( "myFile.dat", "r" );
− Use fscanf to read from the file
• Like scanf, except first argument is a
FILE pointer
fscanf(myPtr, "%d%s%f", &myInt,
&myString, &myFloat);
− Data read from beginning to end
Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 12
Reading Data from a Sequential
Access File (continued)
• More convenient methods of reading a
string with fscanf
− %[characters]: read until all characters are not
found
− %[^characters]: read until any characters is
found.
• Example:
<ID>-<Name>(<Gender>)tab<Birthday>tab<Grade>
09121234-N. T. Dep(Female) 19/09/99 8.5

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 13


Reading Data from a Sequential
Access File (continued)
struct Student {
char STUID[8]; // 19121234
char FullName[30];// N. T. Dep
char Gender[6]; // Female
char Birthday[9]; // 19/09/99
float Grade; // 8.5
};//09121234-N. T. Dep(Female) 19/09/99 8.5
void main() {
Student stu;
FILE *fp = fopen(“students.txt”, “rt”);
if (fp != NULL) {
fscanf(fp, “%[^-]-%[^(](%[^)])\t%[^\t]\t%f”,
&stu.STUID, &stu.FullName, &stu.Gender,
&stu.Birthday, &stu.Grade);
fclose(fp);
}
}Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 14
Demo

• ch10-File01.cpp
• ch10-File02.cpp
• ch10-File03.cpp

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 15


Random Access Files

• Access individual records without searching


through other records
• Instant access to records in a file
• Data can be inserted without destroying other
data
• Data previously stored can be updated or
deleted without overwriting
• Implemented using fixed length records

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 16


Random Access Files (continued)

0 100 200 300 400 500

}byte offsets
}
}
}
}
}
}
100 100 100 100 100 100
bytes bytes bytes bytes bytes bytes

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 17


Creating a Random Access File

• Data in random access files


− Unformatted (stored as "raw bytes")
− All data of the same type (ints, for
example) uses the same amount of
memory
− All records of the same type have a fixed
length
− Data not human readable

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 18


Creating a Random Access File
(continued)
• Unformatted I/O functions
− fwrite
• Transfer bytes from a location in
memory to a file
− fread
• Transfer bytes from a file to a location in
memory

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 19


Creating a Random Access File
(continued)
• Example:
fwrite(&number, sizeof(int), 1,
myPtr);
− &number – Location to transfer bytes from
− sizeof( int ) – Number of bytes to transfer
− 1 – For arrays, number of elements to transfer
− In this case, "one element" of an array is being
transferred
− myPtr – File to transfer to or from

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 20


Creating a Random Access File
(continued)
• Writing structs
fwrite(&myObject, sizeof(myStruct), 1, myPtr );
− sizeof – returns size in bytes of object in
parentheses
• To write several array elements
− Pointer to array as first argument
− Number of elements to write as third argument

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 21


Reading Data Sequentially from a
Random Access File
• fread: reads a specified number of bytes
from a file into memory
fread( &client, sizeof (struct
clientData), 1, myPtr );
− Can read several fixed-size array elements
• Provide pointer to array
• Indicate number of elements to read
− To read multiple elements, specify in third
argument

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 22


Writing Data Randomly
(continued)
• fseek: sets file position pointer to a
specific position
fseek(pointer, offset, symbolic_constant);
− pointer – pointer to file
− offset – file position pointer (0 is first location)
− symbolic_constant – specifies where in file we
are reading from
• SEEK_SET – seek starts at beginning of file
• SEEK_CUR – seek starts at current location in file
• SEEK_END – seek starts at end of file
Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 23
Writing Data Randomly
(continued)
• rewind: sets the file position to the
beginning
rewind(pointer);
− pointer – pointer to file
• ftell: returns the current file position of the
given stream.
ftell(pointer);
− pointer – pointer to file

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 24


Writing Data Randomly
(continued)
FILE* fp = fopen(“fileName.txt”, “rb”);
fseek(fp, 0L, SEEK_END);
long size = ftell(fp);
printf(“The size of file: %ld\n”, size);

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 25


File Management Functions

• remove: remove a file pointed to


by filename
int remove(const char *filename);
− filename – the file to delete
− The remove function returns zero is
successful, otherwise nonzero
if (remove(“c:\\vc.txt”) == 0)
printf(“The file vc.txt was removed!”);
else
printf(“Cannot remove the file vc.txt!”);

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 26


File Management Functions (cont)

• rename: changes the name of a file. You


must close the file before renaming, as a file
can not be renamed if it is open
int rename(const char *old, const
char *new);
− old – the old file name that will be changed
− New – the new file name to use
− This function returns zero is successful,
otherwise nonzero

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 27


File Management Functions (cont)
if (rename(“c:\\a.txt”, “c:\\BT\b.cpp”) == 0)
printf(“Rename successfully J ”);
else
printf(“Cannot rename this file L ”);

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 28


Demo

• ch10-File04.cpp (Creating a Random Access


File)
• ch10-File05.cpp (Writing Data Randomly)
• ch10-File06.cpp (Reading Data)

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 29


Summary
• The hierarchy of data
• Creating a Sequential Access File
• Reading Data from a Sequential Access File
• Creating a Random Access File
• Writing Data Randomly to a Random Access
File
• Reading Data Sequentially from a Random
Access File

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 30


Reading
File handling in C++
• Chapter 16 - Input/Output Streams (C++
Programming: An Object-Oriented Approach)

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 31


Assignment
Is this program wrong?
void main()
{
FILE *fp;
int c;
if ((fp = fopen("abc.xyz", "rb")) == NULL)
printf("Cannot open file abc.xyz\n");
else
{
while ((c = fgetc(fp)) != EOF)
fprintf(stdout, "%c", c);
fclose(fp);
}

}
Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 32
Assignment
Write a program that uses functions to perform
the following operations:
• Read 3 integers from the keyboard and write
that numbers to a file
• Read 3 integers from the “input.txt” file, solve
quadratic equation (ax2+ bx + c = 0) and write
the results to the “output.txt” file

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 33


Assignment
Write a program that uses functions to perform
the following operations:
• Read n integers from the “input.txt” file, sort
those numbers in ascending order and write
the results to the “output.txt” file
4 è 4
2 5 1 4 è 1 2 4 5

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 34


Assignment
Write a program to do the following functions:
• Write a list of Point to “points.data” file
• Read “points.data” file and print out the list of
points
• Find two most distant points and write them to
“ouput.dat”

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 35


References
• Behrouz A. Forouzan, Richard Gilberg, C++
Programming: An Object-Oriented Approach, 1st Edition,
Hill Education, 2019.
• Trần Đan Thư, Nguyễn Thanh Phương, Đinh Bá Tiến,
Trần Minh Triết, Nhập môn lập trình, NXB Khoa Học Kỹ
thuật, 2011.
• Đặng Bình Phương, Bài giảng nhập môn lập trình, 2009

Introduction to Programming – Nguyen Le Hoang Dung Updated on 11/25/19 36

You might also like