Topic 11 - File Operations

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Topic 11

File Operations
ECE1016 – Computer and Program Design
ERC1036 – Computer and Programming

© Multimedia University
Objectives

• To introduce the basic of file handling in C


• To demonstrate the standard functions used to handle
standard I/O in C

© Multimedia University 2
Outline

• Introduction
• Basic File Operations
• Examples of File Handling

© Multimedia University 3
Introduction
Topic 11: File Operations

© Multimedia University 4
Introduction

• Reading and writing external files are important for practical


programs.
• Why files are needed?
1. When a program is terminated, the entire data is lost. Storing in a file
will preserve your data even if the program terminates.

2. 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 a few commands in C.

3. You can easily move your data from one computer to another without
any changes.

© Multimedia University 5
Types of Files

• Generally, there are two types of files:


1. Text files
• Text files are the normal .txt files.
• Storing data as plain text.

2. Binary files
• Binary files are the .bin files.
• Instead of storing data in plain text, they store it in the binary form
(0's and 1's).

• We will deal with text files only in this topic.

© Multimedia University 6
Basic File Operations
Topic 11: File Operations

© Multimedia University 7
Basic File Operations

• Four basic operations on files:


1. Opening a file
2. Closing a file
3. Reading a file
4. Writing a file

© Multimedia University 8
1. Opening a file

• fopen()function is used for opening/creating a file.


• Syntax:
FILE pointer_name = fopen ("file_name", "Mode");

• Mode – refers to the operation that will be performed on the file.


FILE *fp = fopen("C:\\myfiles\\newfile.txt", "r");

• Example:
FILE *fp;
fp = fopen("C:\\myfiles\\newfile.txt", "r");

• The mode ‘r’ means “read only mode”

© Multimedia University 9
File Opening Checking

How to check whether the file has opened successfully?


• If file does not open successfully, the pointer will be assigned
to a NULL value.
• The error display message code is normally added in the
code. For example:
FILE *fpr;
fpr = fopen("C:\\myfiles\\newfile.txt", "r");

if (fpr == NULL)
{
puts("Error while opening file");
return 1;
}

© Multimedia University 10
File Opening Modes
Mode Description Remarks
r Open for reading fopen() returns NULL if the file does not exist.
w Open for writing If the file exists, its contents are overwritten.
If the file does not exist, it will be created.
a Open for append. Data is If the file does not exist, it will be created.
added to the end of the file
r+ Open for both reading and fopen() returns NULL if the file does not exist.
writing
w+ Open for both reading and If the file exists, its contents are overwritten.
writing If the file does not exist, it will be created.
a+ Open for both reading and If the file does not exist, it will be created.
appending.

© Multimedia University 11
2. Closing a file

• fclose()function is used for closing a file.


• Syntax:
fclose(pointer_name);

• Example:
FILE *fp;
fp = fopen("C:\\myfiles\\newfile.txt", "r");
fclose(fp);

© Multimedia University 12
Example 1: Opening and Closing a File
#include <stdio.h>

int main(){
FILE *fPtr; /* File pointer declaration */

/* Create file for Read only */


fPtr = fopen("input.txt","r");

if (fPtr == NULL) {/* Catch error in fopen function */


printf("Error in opening file\n");
return 1;
}

fclose(fPtr); /* Close file */

return 0;
}

© Multimedia University 13
3. Reading a file

• Three common functions to read a file:


1. fgetc(file_pointer)
2. fgets(str, size, file_pointer)
3. fscanf(file_pointer, specifier, variable)

• EOF (End of File) is the last character in file. The function


getc() returns EOF on success.

• feof can be used to determine end of file is reached. If the


EOF marker is reached, a non-zero value is returned,
otherwise 0 is returned.

© Multimedia University 14
4. Writing a file

• Three common functions to write a file:


1. fputc(char, file_pointer)
2. fputs(str, file_pointer)
3. fprintf(file_pointer, specifier, variable)

© Multimedia University 15
Read and Write a File
Equivalent
Function standard Usage
functions
fgetc (FILE *fPtr) getc Reads and returns the next character from
the stream fPtr.
fgets (char *Str, int n, gets Reads characters from stream fPtr into the
FILE *fPtr) string pointed to by Str.
The integer argument n indicates the
maximum number of characters that the
buffer Str can store.
fscanf (FILE *fPtr, const scanf Converts read characters according to the
char *format, ...) format string and the values created are
stored through the argument pointers.
fputc (int c, FILE* fPtr) putc Writes the character c to the file stream
fPtr.
fputs (const char *Str, puts Writes the string Str (excluding the
FILE *fPtr) terminating '\0') to the stream fPtr.
fprintf (FILE *fPtr, const printf Writes formatted data to the file stream fPtr.
char *format, arg0...
argn)

© Multimedia University 16
Examples of File Handling
Topic 11: File Operations

© Multimedia University 17
Example 2: Write to a text file
#include <stdio.h>
#include <stdlib.h>

int main()
{
int num;
FILE *fptr;

fptr = fopen("input.txt","w");

if(fptr == NULL)
{
printf("Error in opening file!\n");
return 1;
}

printf("Enter num: ");


scanf("%d",&num);

fprintf(fptr,"%d",num);
fclose(fptr);

return 0;
}
© Multimedia University 18
Example 3: Read from a text file
#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *fptr;
int num;

if ((fptr = fopen("input.txt","r")) == NULL){


printf(" Error in opening file!\n ");
return 1;
}

/*read the input from file 'input.txt'*/


fscanf(fptr,"%d", &num);

printf("Value of n = %d\n", num);


fclose(fptr);

return 0;
} © Multimedia University 19
Example 4: Prompt user for filename and display file
content on screen
#include <stdio.h>
int main()
{
FILE *fPtr;
int c ;
char filename[40] ;
printf("Enter file to be displayed: ");
gets( filename ) ;
fPtr = fopen( filename, "r");

if (fPtr == NULL) {
printf("Error in opening file\n");
return 1;
}

c = fgetc(fPtr) ;
while (c != EOF )
{ putc(c,stdout);
c = fgetc (fPtr); }

fclose(fPtr);
return 0;
}
© Multimedia University 20
Example 5a: Get input from user and save to a text file.
#include <stdio.h>
int main( ) {
int i; //Loop variable
int number; //Stores phone number entered
FILE *fPtr; //File pointer declaration
fPtr = fopen("phone.txt","w"); //Creates file for Write only

if (fPtr == NULL) { //Catches error in fopen function


printf("Error in opening file\n");
return 1;
}

printf("Enter the phone numbers dialled\n");


//Get 5 sets of data from user and save to phone.txt

for (i=0; i<5; i++){


printf("Phone number %d:", i+1);
scanf("%d", &number);
fprintf(fPtr, "%d\n", number);
}

fclose(fPtr); //Closes file


return 0;
} © Multimedia University 21
Example 5a: Sample output

Sample output:

Enter the phone numbers dialled


Phone number 1:1234
Phone number 2:9870
Phone number 3:8888
Phone number 4:5333
Phone number 5:6545

© Multimedia University 22
Example 5b: Read data from phone.txt file and display
on screen
#include <stdio.h>
int main( ) {
int i; //Loop variable
int number; //Stores phone number read from file

FILE *fPtr; //File pointer declaration


fPtr = fopen("phone.txt","r"); //Creates file for Read only
if (fPtr == NULL) { //Catches error in fopen function
printf("Error in opening file\n");
return 1;
}

//Read data from phone.txt and display the data on computer


screen
printf("Phone number dialled:\n");
for (i=0;i<5;i++){ Phone number dialled:
fscanf(fPtr, "%d",&number); Number 1: 1234
printf("Number %d:\t %d\n",i+1,number);Number 2: 9870
}
Number 3: 8888
fclose(fPtr); //Closes file Number 4: 5333
return 0; Number 5: 6545
}
© Multimedia University 23
Example 5c: Appending a text file
#include <stdio.h>
int main( ) {
int number; //Stores the new phone number entered

FILE *fPtr; //File pointer declaration


fPtr = fopen("phone.txt","a+");//Creates file for Append & Read modes
if (fPtr == NULL) { //Catches error in fopen function
printf("Error in opening file\n");
return 1;
}

printf("Enter the new phone number dialed\n");


scanf("%d", &number);
fprintf(fPtr, "%d\n", number);

fclose(fPtr); //Closes file

return 0;
}

© Multimedia University 24
Example 5c: Sample Output

Sample output:
Enter the new phone number dialed
9999

© Multimedia University 25
Summary

• To open and close a file, use fopen and fclose,


respectively.

• To read or write from a sequential file, file functions similar


to the standard input/output functions can be used: fgetc,
fscanf, fgets, fputc, fprintf and fputs.

© Multimedia University 26

You might also like