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

File Processing: Subject: COMP6047 Algorithm and Programming Year: 2019

This document provides an overview of file processing in C programming. It discusses key concepts such as file definition, opening and closing files, reading from and writing to files using functions like fopen(), fclose(), fgetc(), fputc(), fgets(), fputs(), fscanf(), fprintf(), fwrite(), and fread(). Examples are given to demonstrate reading and writing files using these functions. The learning outcomes are to demonstrate the ability to apply file read and write operations to text and binary files.

Uploaded by

marvelius putra
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)
66 views

File Processing: Subject: COMP6047 Algorithm and Programming Year: 2019

This document provides an overview of file processing in C programming. It discusses key concepts such as file definition, opening and closing files, reading from and writing to files using functions like fopen(), fclose(), fgetc(), fputc(), fgets(), fputs(), fscanf(), fprintf(), fwrite(), and fread(). Examples are given to demonstrate reading and writing files using these functions. The learning outcomes are to demonstrate the ability to apply file read and write operations to text and binary files.

Uploaded by

marvelius putra
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/ 36

Subject : COMP6047

ALGORITHM AND PROGRAMMING


Year : 2019

File Processing
Learning Outcomes
At the end of this session, student will be able to:
• Demonstrate ability to apply file read, write data to a text file or
binary (LO2, LO3 & LO4)

COMP6047 - Algorithm and Programming 2


Sub Topics
File Processing:
– Files and Streams
– File Definition
– Open File
– Close File
– Input File
– Output File
– Program Examples
– Exercise

COMP6047 - Algorithm and Programming 3


Files and Streams
Streams Definition
• To keep key in data from keyboard need to be saved at
secondary storage device as a data file.
• Stream is a sequence of character. All input and output
data is a stream. C sees file as a stream.

COMP6047 - Algorithm and Programming 4


Files and Streams
• When a C program run, there are three (3) standard streams
activated:
1. Standard Input Stream
Controlling input stream from keyboard
2. Standard Output Stream
Controlling output stream to the monitor
3. Standard Error Stream
Controlling the error messaging

• Each stream associated with a file.

COMP6047 - Algorithm and Programming 5


Files and Streams
• File Definition
– File is a collection of record
– Record is a collection of field
– Field is a block of byte
– Byte is collection of bit

COMP6047 - Algorithm and Programming 6


Files and Streams
• Opening a file ordering a pointer returned to the initiator. The
Pointer is pointing to a data structure with FILE type defined in
stdio.h

Standard input stream stdin


Standard output stream stdout
Standard error stream stderr

Stream File pointer

COMP6047 - Algorithm and Programming 7


File Definition
typedef struct {
int level; // fill/empty level of
buffer
unsigned flags; // File status flags
char fd; // File descriptor
unsigned char hold; // Unget char if no buffer
int bsize; // Buffer size
unsigned char *buffer; // Data transfer buffer
unsigned char *curp; // Current active pointer
unsigned istemp; // Temporary file indicator
short token; //Used for validity checking
} FILE;

COMP6047 - Algorithm and Programming 8


File Definition
• TEXT FILE saved in a text format or ASCII File
– Storage size depends on its data: 10000 needs 5 byte
– Can be open using standard text editor application
– or c:>TYPE file_name

• BINARY FILE storing numerical data in affixed format in


line with micro-processor format definition (example:
format sign-magnitude 2’s complement).

COMP6047 - Algorithm and Programming 9


Buffer Area
• Buffer area is part of the memory used as a temporary space
before data moved to a file.

• Syntax:
FILE *fp;
Where fp is a file pointer pointing to the start of the buffer area.

• Also known as stream pointer.

COMP6047 - Algorithm and Programming 10


Open File
• Opening a File using fopen():
FILE *fopen (const char *filename, const char
*mode );

• fopen() defined at <stdio.h>

• fopen() return a pointer to the start of a buffer area. Null will


be returned if file unable to open.

COMP6047 - Algorithm and Programming 11


Open File
• Possible mode value :
Mode Description
“r” opening a file to be read.
“w” creating a file to be written.
“a” opening a File for data append.
“r+” opening a File for read/write.
“w+” creating file for read/write.
“a+” opening a File for read/append
“rb” opening a File (binary) to be read.
“wb” creating a file (binary) for write operation.

COMP6047 - Algorithm and Programming 12


Close File
• Closing a File using fclose():

int fclose (FILE *stream);

• fclose() defined at <stdio.h>


• fclose() will return 0 if successful, and EOF if error
• EOF (End Of File) equals to -1
• fclose() will release the buffer area and immediately send
the remaining data to file.

COMP6047 - Algorithm and Programming 13


Close File
• Closing a File using fcloseall():

int fcloseall (void);

 Close all active stream except: stdin, stdout,


stdprn, stderr, and stdaux.
 Will return the number of stream closed if
successful, and return EOF instead.
 Header file <stdio.h>

COMP6047 - Algorithm and Programming 14


Input & Output File
• fgetc (INPUT)
– Read one character from a file
– fgetc(stdin) equivalent with getchar()
– Syntax : int fgetc( FILE *stream );
– Return the character when successful, and EOF while error

• fputc (OUTPUT)
– Writing one character to a file
– fputc('a', stdout) similar with putchar( 'a' )
– Syntax: int fputc( int c, FILE *stream );
– Return a character when successful, and EOF if error

COMP6047 - Algorithm and Programming 15


Input & Output File
• fgets (INPUT)
– Syntax: char *fgets( char *string, int n, FILE *stream );
– Read one line from a file that ended with new line, or at
maximum of n-1 number of character.
– Return a string if successful and NULL while error

• fputs (OUTPUT)
– Writing a line to a file
– Syntax: int fputs( const char *string, FILE *stream );
– Return non-negative value while successful and EOF if error.

COMP6047 - Algorithm and Programming 16


Input & Output File
• fscanf (INPUT)
– Syntax:
int fscanf( FILE *stream, const char *format [,
argument ]... );
– Read data from file inline with the scanf formatting.
– Return the number of field read while successful, and EOF if error

• fprintf (OUTPUT)
– Syntax:
int fprintf( FILE *stream, const char *format [, argument ]...);
– Writing data to a file using the printf format.
– Return number of byte written if successful and negative value if
error.

COMP6047 - Algorithm and Programming 17


Input & Output File
• fwrite
– syntax: size_t fwrite( const void *buffer, size_t size, size_t count,
FILE *stream );
– Writing a block of data in the buffer area to the file
– Return number of byte data written, and error otherwise.
• fread
– Syntax: size_t fread( void *buffer, size_t size, size_t count, FILE
*stream );
– Read a block size of data from a file
• feof
– Syntax : int feof( FILE *stream );
– Finding out if the pointer has reached end-of-file
– Return 0 if not end-of-file

COMP6047 - Algorithm and Programming 18


Input & Output File
• Example using fwrite():

fwrite( &mhs, sizeof( mhs ), 1, fp );

– &mhs = data origin location


– sizeof(mhs) = return the size of mhs
– 1 => one time write sizeof(mhs)
– fp = file pointer

COMP6047 - Algorithm and Programming 19


Program Examples
• Example
#include <stdio.h>
void main( void ) {
FILE *stream;
char *p, buffer[] = "This is the line of output\n";
int ch; ch = 0;
stream = stdout;
for( p = buffer; (ch != EOF) && (*p != '\0'); p++ )
ch = putc( *p, stream );
}
Output:
This is the line of output
COMP6047 - Algorithm and Programming 20
Program Examples
• Example reading file fgetc.c
#include <stdio.h>
int main(void)
{
char ch; FILE *fp;
fp=fopen("fgetc.c","r");
if(fp==NULL){
printf("File fgetc.c can’t be opened\n"); exit(1);
}
while(!feof(fp)){
ch=fgetc(fp); printf("%c",ch);
}
fclose(fp);
return 0;
} COMP6047 - Algorithm and Programming 21
Program Examples
• Example writing string to file test.txt using fputc
#include <stdio.h>
int main(void)
{
FILE *fp; int i;
char ss[80]=“This statement is saved to test.txt using fputc";
fp=fopen("test.txt","w");
if(fp==NULL){
printf("File test.txt can’t be created\n"); exit(1);
}
for(i=0; i<strlen(ss); i++) fputc(ss[i], fp);
fclose(fp);
return 0;
}
COMP6047 - Algorithm and Programming 22
Program Examples
• Example reading file fgets.c using fgets
#include <stdio.h>
int main(void)
{
FILE *fp;
char ss[80];
fp=fopen("fgets.c","r");
if(fp==NULL){
printf("File fgets.c can’t be opened\n"); exit(1);
}
while(fgets(ss, 80, fp)) printf("%s",ss);
fclose(fp);
return 0;
}
COMP6047 - Algorithm and Programming 23
Program Examples
• Example writing a string to file test.txt using fputs
#include <stdio.h>
int main(void)
{
FILE *fp;
char ss[80]=“This statement’s saved to file test.txt using fputs";
fp=fopen("test.txt","w");
if(fp==NULL){
printf("File test.txt can’t be created\n");
exit(1);
}
fputs(ss, fp);
fclose(fp);
return 0;
} COMP6047 - Algorithm and Programming 24
Program Examples
• Example writing data to file test.txt using fprintf
#include <stdio.h>
int main(void)
{
FILE *fp;
fp=fopen("test.txt","w");
if(fp==NULL){
printf("File test.txt can’t be created\n");
exit(1);
}
fprintf(fp,"%d %s %f\n",1,“Amir", 3.95);
fprintf(fp,"%d %s %f\n",2,“Tono", 3.15);
fclose(fp);
return 0;
} COMP6047 - Algorithm and Programming 25
Program Examples
• Example reading data from file test.txt using fscanf
#include <stdio.h>
int main(void)
{
FILE *fp; int no; char name[20]; float gpa;
fp=fopen("test.txt","r");
if(fp==NULL){
printf("File test.txt can’t be opened\n");
exit(1);
}
fscanf(fp,"%d %s %f",&no,name, &gpa);
printf("%d %s %f\n",no,name,gpa);
fscanf(fp,"%d %s %f",&no,name, &gpa);
printf("%d %s %f\n",no,name,gpa);
fclose(fp); return 0;
COMP6047 - Algorithm and Programming 26
}
Program Examples
• Example writing data to binary file test.dat using fwrite

#include <stdio.h>

int main(void)
{
FILE *fp;
int Arr[]={1,2,3,4,5};
fp=fopen("test.dat","w");
if(fp==NULL){
printf("File test.dat can’t be created\n");
exit(1);
}
fwrite(Arr,sizeof(Arr),1,fp);
fclose(fp);
return 0;
}
COMP6047 - Algorithm and Programming 27
Program Examples
• Example reading data from binary file test.dat using fread
#include <stdio.h>
int main(void)
{
FILE *fp; int i;
int Arr[5];
fp=fopen("test.dat","r");
if(fp==NULL){
printf("File test.dat can’t be opened\n");
exit(1);
}
fread(Arr,sizeof(Arr),1,fp);
for(i=0; i<5; i++) printf("%d ",Arr[i]);
fclose(fp);
return 0;
}

COMP6047 - Algorithm and Programming 28


Exercise
1. A text file contain birth date of some employees with format dd/mm/yy:
• 01/06/50
• 03/06/51
• 10/02/54
• 08/01/48
• 26/08/51
• 27/04/54
• 21/09/51
• … and so on
Read the file using C and find out how many employees with age:
– above 51
– between 44 – 51
– between 36 – 43
– between 28 – 35
– below 28
(note : age = now – birth date)

COMP6047 - Algorithm and Programming 29


Exercise
2. struct Mhs{
char name[20];
int nim;
float gpa;
};

Create a binary file using fwrite, to store 5 record of Mhs data


structure above. Name, nim and cummulative achievement (gpa)
is inputted from the keyboard.
File name = Mhs.dat

COMP6047 - Algorithm and Programming 30


Exercise
3. Read file Mhs.dat from previous exercise using fread(), then
display it to the monitor using the following format:
Nim Name GPA
------ -------- ----

4. Open file Mhs.dat from prev exercise, then append 5 record of


student data using keyboard

COMP6047 - Algorithm and Programming 31


Exercise
5. Describe with example function rewind() with the following syntax:
void rewind( FILE *stream );

6. Describe with example function fseek() with the following syntax :


int fseek( FILE *stream, long offset, int origin );

7. Describe with example function ftell() with the following syntax:


long ftell( FILE *stream );

8. Describe how to find out the size of a file?

COMP6047 - Algorithm and Programming 32


Exercise
9. Create a program to copy a file as in DOS command:
C>copy test.c try.c

10. Create a program to delete a file as in DOS command:


C> del test.c

COMP6047 - Algorithm and Programming 33


Summary
• Stream is a sequence of character. All input and output data is
a stream. C sees file as a stream.
• File Definition
– File is a collection of record
– Record is a collection of field
– Field is a block of byte
– Byte is collection of bit

COMP6047 - Algorithm and Programming 34


References
• Paul Deitel & Harvey Deitel. (2016). C how to program : with an
introduction to C++. 08. Pearson Education. Hoboken. ISBN:
9780133976892. Chapter 11
• Disk File Input and Output: Part I:
http://aelinik.free.fr/c/ch21.htm
• Disk File Input and Output: Part II:
http://aelinik.free.fr/c/ch22.htm
• File Handling in C Language:
http://www.mycplus.com/tutorials/c-programming-tutorials/file-h
andling/
• File:
http://www.cs.iupui.edu/~n305/spring11/book_slides/chtp6_11.
ppt
COMP6047 - Algorithm and Programming 35
END

COMP6047 - Algorithm and Programming 36

You might also like