0% found this document useful (0 votes)
30 views46 pages

Slot26 27 28 Text Files

This document discusses text files in C programming. It defines what a file is and the different types of files, including text and binary files. It explains how data is stored and accessed in files using functions like fopen(), fclose(), fgetc(), fputs(), fscanf(), fprintf() and others. The steps to access a file include opening it, determining the read or write position, reading or writing data in a loop, and closing the file. Filenames can be specified using absolute or relative paths.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views46 pages

Slot26 27 28 Text Files

This document discusses text files in C programming. It defines what a file is and the different types of files, including text and binary files. It explains how data is stored and accessed in files using functions like fopen(), fclose(), fgetc(), fputs(), fscanf(), fprintf() and others. The steps to access a file include opening it, determining the read or write position, reading or writing data in a loop, and closing the file. Filenames can be specified using absolute or relative paths.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Programming Fundamentals using C

Text Files

Module H: Files
Programming Fundamentals using C

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

Text Files 2
Programming Fundamentals using C

Text Files 3
Programming Fundamentals using C

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 4
Programming Fundamentals using C

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 5
Programming Fundamentals using C

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 6
Programming Fundamentals using C

Text Files 7
Programming Fundamentals using C

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 8
Programming Fundamentals using C

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 9
Programming Fundamentals using C

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 10
Programming Fundamentals using C

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 11
Programming Fundamentals using C

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 12
Programming Fundamentals using C

6- Steps for Accessing a File


Reading file to variables Writing variables to file

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


// function // function
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.tcxt”

Text Files 13
Programming Fundamentals using C

To specify a filename
D:

T1 T2 T3

T21 f4.txt
T22

T221 T222 f3.txt


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

Text Files 14
Programming Fundamentals using C

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 15
Programming Fundamentals using C

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 16
Programming Fundamentals using C

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 17
Programming Fundamentals using C

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 18
Programming Fundamentals using C

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 19
Programming Fundamentals using C

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 20
Programming Fundamentals using C

Demonstration 1…

Text Files 21
Programming Fundamentals using C

Demonstration 1…

Text Files 22
Programming Fundamentals using C

Demonstration 1…

argCount=1 argCount=2

args[0]: name of the program


args[1]: parameter of the
program

Text Files 23
Programming Fundamentals using C

Demonstration 1…

Function for printing the content of a text file

Text Files 24
Programming Fundamentals using C

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 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.

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

Text Files 25
Programming Fundamentals using C

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 26
Programming Fundamentals using C

Demonstration 2…

Text Files 27
Programming Fundamentals using C

Demonstration 2…

Text Files 28
Programming Fundamentals using C

Demonstration 2…

Text Files 29
Programming Fundamentals using C

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 30
Programming Fundamentals using C

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 31
Programming Fundamentals using C

Demonstration 3….

Text Files 32
Programming Fundamentals using C

Demonstration 3…

Text Files 33
Programming Fundamentals using C

Demonstration 3…

Text Files 34
Programming Fundamentals using C

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 35
Programming Fundamentals using C

Demonstration 4…

Text Files 36
Programming Fundamentals using C

Demonstration 4…

Text Files 37
Programming Fundamentals using C

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 38
Programming Fundamentals using C

Demonstration 5…

Text Files 39
Programming Fundamentals using C

Demonstration 6: rewind(FILE*)

Text Files 40
Programming Fundamentals using C

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 41
Programming Fundamentals using C

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 42
Programming Fundamentals using C

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 43
Programming Fundamentals using C

Summary

Text Files 44
Programming Fundamentals using C

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 45
Programming Fundamentals using C

Thank You

Text Files 46

You might also like