FILE PROCESSING
BEEC 1313 PROGRAMMING FUNDAMENTAL
CONTENTS
Why do files processing
Types of files
File operations
Opening a file
Read/write to a file
Close a file
Why do file processing in programming?
file is a place on your physical disk where information is stored.
When a program is terminated
the entire data is lost
storing in a file will preserve your data even if the program terminates.
If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of
the file using few commands in C.
easily move the data from one computer to another without any changes.
TYPES OF FILES
TEXT FILES BINARY FILES
normal .txt files Binary files are mostly the .bin files in your
can be easily create using Notepad or any computer.
simple text editors.
Instead of storing data in plain text, they
When open those files, all the contents store it in the binary form (0's and 1's).
within the file can be seen as plain text. You
can easily edit or delete the contents. They can hold higher amount of data, are
They take minimum effort to maintain, are not readable easily and provides a better
easily readable, and provide least security security than text files.
and takes bigger storage space.
FILE OPERATIONS
Four major operations on a file:
Creating a new file
Opening an existing file
Reading from OR writing to a file
Closing a file
WORKING WITH FILES
Before working with files, a pointer to a file must be created.
How?
FILE *pointer_name;
FILE is the reserve word for file type in C language
Example:
FILE *file_ptr;
OPENING A FILE
Can be done by using the fopen() function – available in stdio.h
library
How?
filepointer = fopen(“filename”, “mode”);
Example, if you have a textfile called mytextfile.txt in current
working directory and you want to open it for reading:
file_ptr = fopen (“mytextfile.txt”, “r”);
File opening mode (1)
File Mode Meaning of Mode During Inexistence of file
r Open for reading. If the file does not exist, fopen() returns NULL.
rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL.
If the file exists, its contents are overwritten. If the
w Open for writing.
file does not exist, it will be created.
If the file exists, its contents are overwritten. If the
wb Open for writing in binary mode.
file does not exist, it will be created.
Open for append. i.e, Data is added to
a If the file does not exists, it will be created.
end of file.
Open for append in binary mode. i.e,
ab If the file does not exists, it will be created.
Data is added to end of file.
File opening mode (2)
File Mode Meaning of Mode During Inexistence of file
r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.
Open for both reading and writing
rb+ If the file does not exist, fopen() returns NULL.
in binary mode.
If the file exists, its contents are overwritten. If the file
w+ Open for both reading and writing.
does not exist, it will be created.
Open for both reading and writing If the file exists, its contents are overwritten. If the file
wb+
in binary mode. does not exist, it will be created.
Open for both reading and
a+ If the file does not exists, it will be created.
appending.
Open for both reading and
ab+ If the file does not exists, it will be created.
appending in binary mode.
CLOSING A FILE
The file (both text and binary) should be closed after
reading/writing.
Closing a file is performed using library function fclose().
How?
fclose (filepointer);
Example:
fclose (file_ptr);
Example 1
In this example: #include <stdio.h>
A textfile called output.txt is opened
In writing mode int main(){
FILE *fileptr;
fileptr = fopen(“output.txt”,”w”);
//DO something on the file
//need to be closed once completed
fclose (fileptr);
}
GENERAL FILE PROCESSING FLOW
Declare file Open the Check file Manipulate Close the
pointer file status file (R/W) file
Not compulsory, but recommended
especially for read mode
READING FROM A FILE
Method 1: using fscanf() function almost similar to scanf()
How?
fscanf(file pointer, placeholder, address of storing variable);
Example: int main(){
int num;
FILE *ptrfile;
ptrfile = fopen(“myfile.txt”,”r”);
if (ptrfile == NULL){
printf(“Error in opening file!\n”);
exit(1);
}
fscanf (ptrfile, “%d”, &num);
printf(“Value of num is %d \n”, num);
fclose (ptrfile);
return 0;
}
READING FROM A FILE
fscanf can be used to read a word only (limited by white spaces)
To read a sentences, need to do repetition!
Method 2: using fgets() function will read the whole line, up to max number of chars set!
How?
fgets (storing variable, number of chars, file pointer);
READING FROM A FILE
Example using fgets:
int main(){
char data[100];
FILE *ptrfile;
ptrfile = fopen(“myfile.txt”,”r”);
if (ptrfile == NULL){ //check file existance
printf(“Error in opening file!\n”);
exit(1);
}
fgets (data, 50, ptrfile); //read up to 50 chars, save in data
printf(“Message read = %s \n”, data);
fclose (ptrfile);
return 0;
}
EXERCISE 1
Predict the output from this program: int main(){
char data[100];
FILE *ptrfile;
mytext.txt: ptrfile = fopen("myfile.txt","r");
if (ptrfile == NULL){
Welcome to Melaka! printf("Error in opening file!\n");
exit(1);
}
fgets (data, 10, ptrfile);
printf("Message read = %s \n", data);
fclose (ptrfile);
return 0;
}
READING FROM A FILE
int main(){
Method 3: using fgetc() function char data[30] = "";
char c;
to read char by char FILE *fp;
fp = fopen("chartext.txt","r");
How? if (fp == NULL){
fgetc(file pointer); printf("Error in opening file!\n");
exit(1);
Example: }
int i=0;
do {
c = fgetc(fp);
data[i] = c;
i++;
} while (!(feof(fp)));
printf("Message read = %s \n", data);
fclose (fp);
return 0;
}
EXERCISE 2
int main(){
Complete the given code in order char modifieddata[40] = "";
to: char c;
FILE *fp;
Read texts from message.txt
fp = fopen(“????","r");
Convert all uppercase if (fp == NULL){
lowercase printf("Error in opening file!\n");
Convert all lowercase exit(1);
uppercase }
int i=0;
Display modified string
??????
message.txt: printf(“modified text= %s \n", modifieddata);
fclose (fp);
Saya berasal dari Negeri Sembilan return 0;
}
EXERCISE 2 (SOLUTIONS)
int main(){ do {
char modifieddata[40] = ""; c = fgetc(fp);
char c; if (isupper(c))
FILE *fp; c = tolower(c);
fp = fopen("message.txt","r"); else if (islower(c))
if (fp == NULL){ c = toupper(c);
printf("Error in opening file!\n"); modifieddata[i] = c;
exit(1); i++;
} } while (!(feof(fp)));
int i=0; printf("modified text = %s \n", modifieddata);
fclose (fp);
return 0;
}
WRITING TO A FILE
Method 1: using fprintf() function almost similar to printf()
How?
fprintf (file pointer, message or value to be written to file);
Example:
int main(){
char str[] = “Thailand missed Penalty”; //create new string str
FILE *outfile;
outfile = fopen(“newfile.txt”,”w”); //open existing newfile.txt or create a new one
if (outfile == NULL){
printf(“Error in opening file!\n”);
exit(1);
}
fprintf (outfile, “%s”, str); //write the message in str into the file
fclose (outfile);
return 0;
}
EXAMPLE OF FILE WRITING
(MEALS ORDERING SLIP)
int main(){ fprintf (outfile, "======================\n");
char food[20], drink[20]; fprintf (outfile, "Table no: %d\n", table);
int food_quantity, drink_quantity, table; fprintf (outfile, "Ordered food: %20s\t", food);
FILE *outfile; fprintf (outfile, "Quantity: %d\n", food_quantity);
outfile = fopen("order.txt","w"); fprintf (outfile, "Ordered drink: %20s\t", drink);
if (outfile == NULL){ fprintf (outfile, "Quantity: %d\n", drink_quantity);
printf("Error in opening file!\n"); fprintf (outfile, "Please be patient while we are
exit(1); preparing the meals. Thanks!\n");
}
printf("Enter table no: "); fclose (outfile);
scanf("%d", &table); return 0;
printf("Enter food: "); }
scanf(" %[^\n]s", &food);
printf("Enter food quantity: ");
scanf(" %d", &food_quantity);
getchar();
printf("Enter drink: ");
scanf("%[^\n]s", &drink);
printf("Enter drink quantity: ");
scanf(" %d", &drink_quantity);
printf("Thank you! Please check your order slip.\n");
QUICK TIP 1 FOR FILE PROCESSING IN
PROGRAMMING
Basic steps when working with a text file:
• Declare file pointer
• Open the file
• Check file opening status
• Read file / write to file
• Close the file
QUICK TIP 2 FOR FILE PROCESSING IN
PROGRAMMING
Functions to read from file:
• fscanf() - read by words
• fgetc() - read by characters
• fgets() - read by lines
Functions to write to file:
• fprintf() - write characters or strings
• fputc() - write characters