You are on page 1of 21

CUIT101/111/114 CUT-SEST 3/24/2017

FILE INPUT
AND OUTPUT
CUIT101/111/114 CUT-SEST 3/24/2017

2 CONTENTS

• What is a file?
• Types of Files
• File Handling Functions
• Example Code
CUIT101/111/114 CUT-SEST 3/24/2017

3 WHAT IS A FILE?

• A collection of bytes stored on secondary storage, e.g. A hard disk


• Bytes make up pixels, characters, integers, pages, paragraphs or
database records.
• Stores data and programs

• Files allow different operations because of their structure


• Different files require specific programs to display and access their
bytes
CUIT101/111/114 CUT-SEST 3/24/2017

4 TYPES OF FILES

• ASCII TEXT(.txt)
• Stores sequences of characters
• Read/write one character at a time (no simultaneous operations)
• Functions actually process data sequentially (even full-line reading functions)
• Character conversions may be done to suit operating system requirements.
• Processed sequentially from beginning to end-of-file (EOF)
• BINARY
• Stores collections of bytes
• No sequential processing of data
• Each byte transferred to/from disk unprocessed
• Allow both sequential access and random-access
• Processed using simultaneous read and write operations
• E.g. Database files
CUIT101/111/114 CUT-SEST 3/24/2017

5 SOME FILE HANDLING FUNCTIONS


(1)
Function Description
1 fopen() Creates a new file or opens an existing file
2 fclose() Closes a file
3 getc() Reads a character from a file
4 putc() Writes a character to a file
5 getw() Reads an integer from a file
6 putw() Writes an integer to a file
7 fscanf() Reads a set of data from a file
8 fprintf() Writes a set of data to a file
CUIT101/111/114 CUT-SEST 3/24/2017

6 SOME FILE HANDLING FUNCTIONS


(2)
Function Description
9 fseek() Sets the file cursor to a desired point
10 ftell() Gives the current file cursor position in the file
11 rewind() Sets the file cursor to the beginning of the file
12 fread() Reads bytes from a binary file
13 fwrite() Writes bytes to a binary file
14 fgets() Reads a particular length of string from a file
15 fgetc() Reads a character from a file
16 feof() Returns 1(true) if EOF has been reached, otherwise
returns 0(false)
CUIT101/111/114 CUT-SEST 3/24/2017

7 DEFINING A FILE POINTER

• FILE *file_ptr; //pointer to a file object


CUIT101/111/114 CUT-SEST 3/24/2017

8 OPENING A FILE

• #define MYFILE "stud_pers.txt"


• file_ptr = fopen(MYFILE, “option");
CUIT101/111/114 CUT-SEST 3/24/2017

9 TEXT FILE OPENING OPTIONS

Option Meaning
r Opens a text file in read mode
w Opens or creates a text file in write mode
a Opens a file in append mode
r+ Opens a text file in both read and write mode
w+ Opens a text file in both read and write mode
a+ Opens a text file in both read and write mode
CUIT101/111/114 CUT-SEST 3/24/2017

10 BINARY FILE OPENING OPTIONS

Option Meaning
rb Opens a binary file in read mode
wb Opens a binary file in write mode
ab Opens a binary file in append mode
rb+ Opens a binary file in both read and write mode
wb+ Opens a binary file in both read and write mode
ab+ Opens a binary file in both read and write mode
CUIT101/111/114 CUT-SEST 3/24/2017

11 EXITING ON ERROR OF FILE


OPENING
#include <stdlib.h>
#include <stdio.h>
if ( !file_ptr)
{
perror("fopen()");
exit(EXIT_FAILURE);
}
• perror() first prints the message followed by a colon and the implementation-defined
message that describes the most recent error
• exit() immediately terminates entire program execution and also closes all open files
CUIT101/111/114 CUT-SEST 3/24/2017

12 TESTING IF A FILE DOES NOT EXIST

if (file_ptr == NULL)
{
printf("File %s does not exist! \n", MYFILE);
}
CUIT101/111/114 CUT-SEST 3/24/2017

13 APPENDING DATA TO A FILE

file_ptr = fopen(MYFILE, "a");


printf("Enter name: ");
scanf("%s",full_name);
printf("Enter date of birth (dd/mm/yyyy): ");
scanf("%s",dob);
fprintf(file_ptr,"%s \t %s \n",full_name, dob);
fclose(file_ptr);
CUIT101/111/114 CUT-SEST 3/24/2017

14 OVERWRITING A FILE

file_ptr = fopen(MYFILE, "w");


fprintf(file_ptr, "%s", FILE_HEAD);
//do something

fprintf(file_ptr, "%s %s \n", full_name, dob);


fclose(file_ptr);
CUIT101/111/114 CUT-SEST 3/24/2017

15 PRINTING ALL CONTENTS OF A FILE

file_ptr = fopen(FILE1, "r"); do


char c; {
if (file_ptr == NULL)
c = getc(file_ptr);
{
putchar(c); //display on
printf("File %s does not exist! \n",
screen
FILE1);
}while (c!= EOF);
}
else }

{ fclose(file_ptr);
CUIT101/111/114 CUT-SEST 3/24/2017

16 SKIPPING THE FIRST LINE IN A FILE


(1)
• Option 1
#define MAX_LINE_LENGTH 80
char buf[MAX_LINE_LENGTH];
file_ptr = fopen(FILE1, "r");
fgets(buf, MAX_LINE_LENGTH, file_ptr);

• fgets() reads full line, provided you know the length of each line
in the file. If you don’t, use Options 2 or 3.
CUIT101/111/114 CUT-SEST 3/24/2017

17 SKIPPING THE FIRST LINE IN A FILE


(2)
• Option 2
fscanf(file_ptr, "%*[^\n]\n", NULL);
• * indicates to not put the found pattern anywhere
• Whatever is saved is put into NULL, means not saved
• [^\n] means any character except newline.
• \n means newline.
• [^\n]\n means a full text line ending with newline.
CUIT101/111/114 CUT-SEST 3/24/2017

18 SKIPPING THE FIRST LINE IN A FILE


(3)
• Option 3

char c;
do
c = fgetc(file_ptr);
while (c != '\n')

• Read character by character until you get to the end of line marker
CUIT101/111/114 CUT-SEST 3/24/2017

19 SKIPPING LINES THAT START WITH


A SPECIFIC CHARACTER (E.G. #)
char buf[0x1000];
while ( fgets(buf, sizeof(buf), file_ptr) != NULL)
{ if (buf[0] == '#') continue; //immediately go back to while 
// do stuff
}
• while first tests if line is not blank, fgets() gets a full line that is max 1000
characters long

• //0x means what follows is HEX number HENCE 0x1000 = 16 3+ 0*162 + 0*161 +
0*160 = 4096
CUIT101/111/114 CUT-SEST 3/24/2017

20 READING FILE CONTENTS INTO


VARIABLES
char buf[MAX_LINE_LENGTH]; fscanf(file_ptr, "%s %s",
file_ptr = fopen(FILE1, "r"); full_name, dob);
printf("%s \t %s \n", full_name,
fgets(buf, MAX_LINE_LENGTH, dob);
file_ptr);
/*or do something with data in
the variables, e.g. Store in array */
/* If items are stored line by line and
match defined variables, */
} while (!feof(file_ptr));

printf("%s", buf);
do { fclose(file_ptr);
CUIT101/111/114 CUT-SEST 3/24/2017

21 EXERCISE: PROPELLER GEARBOX


EXPERIMENTS
• Note: (variables, units) indicated in brackets. • Bearing in mind that a full record of a trial of
• A propeller operating in open water can be the propeller includes all entered variables and
characterised by several parameters, the propeller all calculated variables, write a program that
torque (a, Nm), the engine torque(b, Nm), the allows the user to
gear ratio (c, fraction), the rotational speed of the • Add a full record to a text file, where each
record occupies its own line.
engine (d, Hz), and the rotational speed of the
• Find a specific record in the file and print it out.
propeller (e, Hz) and the gearbox efficiency (f,
• Delete a specific record in the file
fraction).
• Overwrite a specific record in the file
• These parameters are related as follows: d = ce
• View all records in the file
and a = fcb making d and a calculated fields.
• Each trial of the propeller (identified by a unique • Your program must present a flexible user
integer trial number) adjusts one or more of the menu.and must also make use of structures
non-calculated variables. when working with the records.

You might also like