5 Text-Files
5 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 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
Text Files 12
To specify a filename
D:
T1 T2 T3
f4.txt
T21 T22
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
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
Text Files 22
Demonstration 1…
Text Files 23
7.4- The fgets(), fputs() Functions
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
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
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.
Text Files 35
Demonstration 4…
Text Files 36
Demonstration 5
• Create a file, named array3.txt containing real
numbers.
Text Files 38
Demonstration 6: rewind(FILE*)
Text Files 39
Demonstration 7: fseek(…)
Text Files 40
Summary
Text Files 43
Summary
!=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…
Text Files 47
Bonus…
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:
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