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

5 Text-Files

The document discusses text files and how to access data within text files. It defines what a file is, different file types, and common file functions. The document provides details on opening, reading, writing, positioning and closing text files.

Uploaded by

longngo1234560
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)
26 views

5 Text-Files

The document discusses text files and how to access data within text files. It defines what a file is, different file types, and common file functions. The document provides details on opening, reading, writing, positioning and closing text files.

Uploaded by

longngo1234560
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/ 55

Text Files

Objectives

• What is a file?
• How are data stored in files?
• How to access data in a text file?

Text Files 2
Contents

1- What is a file?
2- File types
3- Ways for accessing files
4- Connecting to a file
5- Declaration a file variable
6- Steps for accessing a file
7- File Functions and Demonstrations
Bonus- Text Files and Parallel Arrays

Text Files 3
1- What is a file?
• A complete, named collection of information,
such as a program, a set of data used by a
program, or a user-created document. A file is
the basic unit of storage that enables a
computer to distinguish one set of information
from another. A file is the “glue” that binds a
conglomeration of instructions, numbers,
words, or images into a coherent unit that a
user can retrieve, change, delete, save, or send
to an output device ( from MS Computer
Dictionary)
Text Files 4
What is a file?...
• A file is not necessarily stored contiguously on
a secondary storage device .
• Disk  Track  Sector
• Some sectors  Cluster
• Unit of disk allocation: Cluster
• This cluster contains data to point to the next
one.
• The contents of a file is accessible after we
have turned the power off and back on at a
later time.
Text Files 5
2- File Types
• The fundamental unit of a file is a byte.
• A file is a stream of bytes.
• A file concludes with a special mark called
the end of file mark (EOF).
• Based on the way used to store data:
– Text file: Unit of data in a file is an ASCII code
of character.
– Binary file: Unit of data in a binary byte  Each
byte on the file is a direct image of the
corresponding byte in memory

Text Files 6
File Types…
Characters 01000001
“ABC” 01000010
01000001 (‘A’) 01000011
01000010 (‘B’) Text file
01000011 (‘C’) 00110010
00000000 (NULL) 00110110
ASCII codes 00110000
of digits
Data 00110010 (‘2’)
00110110 (‘6’)
00110000 (‘0’)
Number
260 (2 bytes) convert
00000001 Binary
00000001 file
00000100
00000100

Text format is more portable than binary format


But binary format is more efficient than text format
Text Files 7
3- Ways for Accessing Files

• Typically, a file consists of records that


we can access in either of two ways
– randomly (like CD's, hard disks) or
– sequentially (like Cassette Tapes).

Text Files 8
4- Connecting to a File
• Os manages hardware  Connecting a file
in a program should be announced to the
OS.
• OS can manage some files concurrently. At a
time, only one file can be accessed 
Information about the opened file must be
maintained for next read or write.
typedef struct _iobuf
stdio.h
{
char* _ptr;
int _cnt;
char* _base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char* _tmpfname;
} FILE;
Text Files 9
4- Connecting to a File

stdio.h
typedef struct _iobuf
{
char* _ptr;
int _cnt;
char* _base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char* _tmpfname;
} FILE;

Text Files 10
5- Declaration
• FILE* identifier ; typedef struct _iobuf
{
• Example char* _ptr;
int _cnt;
#include <stdio.h> char* _base;
int _flag;
FILE* f=NULL; int _file;
• The variable f will be int
int
_charbuf;
_bufsiz;
updated when a specific char* _tmpfname;
} FILE;
file is opened.
• f points to a memory
block having the pre-
defined structure

Text Files 11
6- Steps for Accessing a File
Reading file to variables Writing variables to file

1) Select file by filename 1) Select file by filename

2) Open the file. 2) Open the file


3) Determine the position in the 3) Determine position in the
file will be read. file will be written.
4) Loop 4) Loop
Read file contents to variables. - Set data to variables (if needed)
Process variables. - Write data of variables
5) Close file to file
5) Close file

Generally, we used to process Specify a filename (a string):


a file from the begin of the file. Absolute pathname:
“c:/t1/t11/f1.txt” or
“c:\\t1\\t11\\f1.txt”
File in the current folder: “f1.txt”

Text Files 12
To specify a filename
D:

T1 T2 T3

f4.txt
T21 T22

T221 T222 f3.txt


“f1.txt”
When p.exe “./f1.txt”
executes, the “.\\f1.txt”
directory T222 is T2221 ”T2221/f2.txt”
f1.txt p.exe
the working “./T2221/f2.txt”
(current) directory. “../f3.txt”
f2.txt “D:/T3/f4.txt”

Text Files 13
7- Some Common File Functions
Purpose STDIO.H Syntax
Open a file FILE* fopen(char fname[], char mode[])
Close a opening file int fclose(FILE*)
Read a character int fgetc(FILE*)
Write a character int fputc(char, FILE*)  EOF (-1)
Read a string fgets( char S[], int nbytes, FILE* f);  NULL if EOF
Write a string fputs ( char*, FILE*)
Read a number fscanf ( FILE*, char* format, PointerList)
Write a number fprintf ( FILE*, char* format, VarList)
Test whether the file is EOF? int feof(FILE*)
Rewind to the beginning void rewind (FILE*)
Get the current file position long ftell(FILE*)
Move the current position int fseek (FILE*, long offset, int fromPos)
Rename a closed file rename ( char fName[], char newName[])
Remove a closed file remove ( char fName[])
Text Files 14
7.1- The fopen() function
FILE *fopen(char file_name[], char mode[]);
• file_name parameter is a null-byte terminated
string containing the name of the file.
• mode parameter is a null-byte terminated
string containing the connection mode
– "r" - read from the file,
– "w" - write to the file: if the file exists, truncate its
contents and then write; if the file does not exist,
create a new file and then write to that file,
– "a" - write to the end of the file: if the file exists,
append to the end of the file; if the file does not
exist, create it and then write.

Text Files 15
The fopen() function…
• The other connection modes for text files are
– "r+" - opens the file for reading and possibly writing,
– "w+" - opens the file for writing and possibly
reading; if the file exists, truncates its contents and
then writes to the file; if the file does not exist,
creates a new file and then writes to that file,
– "a+" - opens the file for writing to the end of the file
and possibly reading; if the file exists, appends to
the end of the file; if the file does not exist, creates
it and then writes to the file.
– Modes for binary files: “rb”, “wb”, “r+b”, “w+b”,”a+b”
• fopen returns NULL if the attempt to connect
to the file fails.

Text Files 16
7.2- The fclose() function
int fclose(FILE *); 0: successful, EOF (-1): fail
• File opened writing, fclose writes any data
remaining in the file stream's buffer to the
file and concludes by appending an end of
file mark immediately after the last
character.
• File opened reading, fclose ignores any
data left in the file stream's buffer and
closes the connection.
• fclose can fail if the secondary storage medium
is full, an I/O error occurs or the medium has
been prematurely removed.

Text Files 17
7.3- The fgetc(), fputc() Functions

Return Function Parameter

The next byte read (ASCII int fgetc(FILE* fp) Pointer of the file opened
code)
or EOF(-1) End of File

The character written int fputc( int ch, FILE* fp) Character will be written to
or EOF the file

Text Files 18
Demonstration 1
Write a C-program
that will use command
line to perform writing
a text file from
characters inputted by
user until the keys
Ctrl+Z then ENTER
are pressed.
Syntax of the program:
copy_con filename

Text Files 19
Demonstration 1…

Text Files 20
Demonstration 1…

Text Files 21
Demonstration 1…

argCount=1 argCount=2

args[0]: name of the program


args[1]: parameter of the
program

Text Files 22
Demonstration 1…

Function for printing the content of a text file

Text Files 23
7.4- The fgets(), fputs() Functions

Return Function Parameter


Success: str char* fgets(char* str, int num, FILE* fp) num: Maximum number
Fail: NULL of characters will be read
Success: >=0 int fputs( char* str, FILE* fp) str: string is written
Fail: EOF (-1) will be written to the file

The fputs() function: The null that terminates str is not written and it does not
automatically append a carriage return/linefeed sequence.

The fgets() function reads characters from the file associated with fp into a string
pointed to by str until num-1 characters have been read, a newline character is
encountered, or the end of the file is reached. The string is null-terminated and the
newline character is retained. The function returns str if successful and a null pointer if
an error occurs.

Text Files 24
Demonstration 2

Write a C-program that will performs the


following operations:
- User enters a filename of a text file
- User will enter data to the file line-by-line
until a null string is inputted.
- User will see the content of the file.

Text Files 25
Demonstration 2…

Text Files 26
Demonstration 2…

Text Files 27
Demonstration 2…

Text Files 28
7.5- The fscanf(), fprintf() Functions
Return Function Parameter
- Success: int fscanf(FILE* fp, char* format, They are the same in the
Number of data ListOfVarAddresses) function scanf()
items which are
read
- Fail: 0 or
EOF(-1)
int fprintf( FILE* fp, char* format, They are the same in the
VarList) function printf()

Text Files 29
Demonstration 3

Write a C-program that will perform the


following operations:
- User enters a filename of a text file
- User will enter data to the file line-by-line
until a null string is inputted.
- User will see the content of the file.
(The problem of the previous demo. But, the
functions fscanf() and fprintf() are used.)

Text Files 30
Demonstration 3….

Text Files 31
Demonstration 3…

Text Files 32
Demonstration 3…

Text Files 33
Demonstration 4
• Create a file, named array1.txt. The first number in
the file is number of elements of an integer array. The
later numbers are values of elements.

• Write a C-program that will:


• Read the array contained in the above file.
• Print it’s elements in ascending order to monitor.
• Write it to the file array2.txt using the same format
with the file array1.txt.
Text Files 34
Demonstration 4…

Text Files 35
Demonstration 4…

Text Files 36
Demonstration 5
• Create a file, named array3.txt containing real
numbers.

• Write a C-program that will:


• Print out number of values
• Print out the average of values contained in the
above file.
Text Files 37
Demonstration 5…

Text Files 38
Demonstration 6: rewind(FILE*)

Text Files 39
Demonstration 7: fseek(…)

content for testing fseek function


content for testing fseek function
content for testing fseek function
content for testing fseek function EOF
(2bytes)
content for testing fseek function

content for testing fseek function


content for testing fseek function

Text Files 40
Summary

• File: Related data that are stored in a mass


storage (disks).
• Files are managed by the operating system
(OS).
• OS identifies a file through it’s name.
• To specify a absolute filename in C:
“C:\\f1\\f11\\file1.dat” or “C:/f1/f11/file1.dat”
• To process data in a file: We need to know
format and meaning of each data in file.
Text Files 41
Summary
Purpose STDIO.H Syntax
Open a file FILE* fopen(char fname[], char mode[])
Close a opening fle int fclose(FILE*)
Read a character int fgetc(FILE*)
Write a character int fputc(char, FILE*)  EOF (-1)
Read a string fgets( char S[], int nbytes, FILE* f);  NULL if EOF
Write a string fputs ( char*, FILE*)
Read a number fscanf ( FILE*, char* format, PointerList)
Write a number fprint ( FILE*, char* format, VarList)
Test whether the file is EOF? int feof(FILE*)
Rewind to the beginning void rewind (FILE*)
Get the current file position long ftell(FILE*)
Move the current position int fseek (FILE*, long offset, int fromPos)
Rename a closed file rename ( char fName[], char newName[])
Remove a closed file remove ( char fName[])
Text Files 42
Summary

Text Files 43
Summary

Text ch= fgetc(f); char ch; int fputc(ch,f); Text


file file

fgets(S,nbytes,f); char S[20]; fputs(S,f);

!=NULL or NULL

numeric
fscanf ( f, “%♣” , &x); variable fprintf ( f, “%♣” , x);
x

Return value:
-1 (EOF) end-of- file error or file error
>0 : read successfully

Text Files 44
Thank You

Text Files 45
Bonus:
Text Files and Parallel Arrays
• Actually, each real object contains some data, such as
details of students include name, address and mark.
Some arrays can be used to manage a list of objects.
• Data of a class (group of students) are usually
presented in a file as a table.
• A row in a data table is called as a record.
• Each column in the table is call a field.

Text Files 46
Bonus…

• We call each line


in a text file a
record.
• A record is a
sequence of
characters that
ends with a
newline delimiter.
• Typically, one
record refers to one
entity of
information.

Text Files 47
Bonus…

• To manage a list of records, some arrays are needed.


All elements at the same position present a record.
• If one change is performed on an array (such as
sorting), others may be changed appropriately.

Joseph 12 Le Loi, Q1, TPHCM 7


Dinh Tan Vu 12/66 duong so 3, Qo Vap, TPHCM 8
Miranda 123 Calmette, District 1, HCM City 5
Celine Dion 124 street 8, district 7, HCM City 9

Text Files 48
Bonus…
• Data representing a student include: name, address,
mark.
• A list of students are stored in the file students.txt as
below:

• Write a C-program that will print out the list of


students in descending order based on their marks
then the list will be written to the file students_2.txt
with the same format as the previous file.

Text Files 49
Bonus…

Text Files 50
Bonus…

Text Files 51
Bonus…

Text Files 52
Bonus…

Text Files 53
Bonus…

Text Files 54
Thank You

Text Files 55

You might also like