Escolar Documentos
Profissional Documentos
Cultura Documentos
Operations &
System
Services
Introduction
Objective
To introduce:
basic methods to
manipulate text files in
C programs using
sequential and random
access techniques
Learning Outcome
using appropriate
functions for dynamic
memory allocation
dynamic memory
allocation technique
Overview
File
manipulation
Sequential
access
Random
access
Dynamic
memory
allocation
File
Why?
stderr (Screen)
Redirection
Key
<
>
Redirection
#include <stdio.h>
int main( ) {
printf("Hello World!");
return 0;
}
Redirection
#include <stdio.h>
int main( ) {
char str[100];
gets(str);
printf("%s",str);
return 0;
Redirection
Advantage: simple
File Operations in C
Modes
Sequential
access
Cassette
Random
access
CD
Description
fgetc
fputc
fgets
fputs
fscanf
fprintf
fread
fwrite
Sequential Access
Sequential Access
File pointer advances from first character in the file
towards EOF marker
Sequential file functions:
Read (fgetc, fscanf, fgets)
Write (fputc, fprintf, fputs)
Advantage:
- Simpler code
Limitations:
- Data can be overwritten if not careful.
- Slower access speed
Sequential Access
Function
reading
Equivalent
Usage
standard
functions
getc
Reads and returns the next character from the stream
fPtr.
gets
Reads characters from stream fPtr into the string
pointed to by Str.
The integer argument n indicates the maximum
number of characters that the buffer Str can store.
Reading stops when a newline is read, end-of-file is
encountered, a read error occurs, or n-1 characters
were read.
writing
scanf
putc
printf
puts
feof(FILE *fptr)
This program:
1. creates files to write students ID,
first name, gpa and cgpa
2. read from the students files and
print the data in tabular form.
One file for one student.
The files are named based on student
ID
Opening file
Opening Mode
w
:create file for writing, if file already
existed discard the content
a
:add record to the end of existing file,
appending
w+
:create file for reading & writing, if file
already existed the content is discarded
a+
:read & write from file, writing is done at
end of file
:binary mode
Opening Mode
Mode
Read
Write
Create
Discard
+
b
/
Binary mode
Writing string of
character (name)
into file
Writing formatted
data into file
Reading
Open & create file for
reading only
Reading data
according to
format string
Reading
Closing File
fclose(fptr);
Closing File
Appending
Additional data of total
credit hour taken is to
be added in all
students files
Appending
Rewind
rewind (fPtr);