SlideShare a Scribd company logo
1 of 34
1
Topics
• File Handling in C
• Basic File I/O Functions
• Example
11/12/15
File
File – place on disk where group of related
data is stored
E.g. your C programs, executables
High-level programming languages support
file operations
Naming
Opening
Reading
Writing
Closing
3
File Handling in C
• Files need to be opened before use.
– Associate a "file handler" to each file
– Modes: read, write, or append
• File I/O functions use the file handler (not
the filename).
• Need to close the file after use.
• Basic file handling functions: fopen(),
fclose(), fscanf(), fprintf().
4
File I/O Example
• Write a program which:
– inputs a list of names from a file called
names.lst
– counts the number of names in the list
– asks a mark for each name in the file
– outputs the name and corresponding mark
to the file names_marks.dat
• Note: the tasks above are not necessarily
accomplished in that order.
5
File I/O (Header)
• Step 0: Include stdio.h.
#include <stdio.h>
int main()
{
...
return 0;
}
6
File I/O (File Pointer)
• Step 1: Declare a file handler (i.e. file
pointer) as FILE * for each file.
int main()
{
FILE *inputfile = NULL;
FILE *outputfile = NULL;
FILE *currentfile = NULL;
...
return 0;
}
7
File I/O (Open)
• Step 2: Open file using fopen().
int main()
{
FILE *inputfile = NULL;
FILE *outputfile = NULL;
FILE *currentfile = NULL;
inputfile = fopen(“Names.txt”, “r”);
outputfile = fopen(“marks.dat”, “w”);
currentfile = fopen(“logFile.txt”, “a”);
...
return 0;
}
8
File I/O (Open)
• Step 2: Open file using fopen().
int main()
{
FILE *inputfile = NULL;
FILE *outputfile = NULL;
FILE *currentfile = NULL;
inputfile = fopen(“Names.txt”, “r”);
outputfile = fopen(“marks.dat”, “w”);
currentfile = fopen(“logFile.txt”, “a”);
...
return 0;
}
File name
9
File I/O (Open)
• Step 2: Open file using fopen().
int main()
{
FILE *inputfile = NULL;
FILE *outputfile = NULL;
FILE *currentfile = NULL;
inputfile = fopen(“Names.txt”, “r”);
outputfile = fopen(“marks.dat”, “w”);
currentfile = fopen(“logFile.txt”, “a”);
...
return 0;
}
Mode
r : read
w : write
a : append
Warning: The "w" mode
overwrites the file, if it exists.
10
File I/O (Open)
• Step 2: Open file using fopen().
int main()
{
FILE *inputfile = NULL;
FILE *outputfile = NULL;
FILE *currentfile = NULL;
inputfile = fopen(“Names.txt”, “r”);
outputfile = fopen(“marks.dat”, “w”);
currentfile = fopen(“logFile.txt”, “a”);
...
return 0;
}
Associate a file handler for
every file to be used.
11
File I/O (Error Check)
• Step 3: Check if file is opened successfully.
int main()
{
FILE *inputfile;
inputfile = fopen(“Names.txt”, “r”);
if (inputfile == NULL)
{
printf(“Unable to open input file.n”);
return 1;
}
...
return 0;
}
12
File I/O (Error Check)
• Step 3: Check if file is opened successfully.
int main()
{
FILE *inputfile;
inputfile = fopen(“Names.txt”, “r”);
if (inputfile == NULL)
{
printf(“Unable to open input file.n”);
return 1;
}
...
return 0;
}
File handler
becomes NULL
when an fopen()
error occurs.
13
File I/O (Error Check)
• Step 3: Check if file is opened successfully.
int main()
{
FILE *inputfile;
inputfile = fopen(“Names.txt”, “r”);
if (inputfile == NULL)
{
printf(“Unable to open input file.n”);
return 1;
}
...
return 0;
}
Ends program
if inside main ( )
function.
14
File I/O (Input)
• Step 4a: Use fscanf() for input.
#include <stdio.h>
#define MAXLEN 100
int main()
{
FILE *inputfile = NULL;
char name[MAXLEN];
int count;
15
File I/O (Input)
• Step 4a: Use fscanf() for input.
#include <stdio.h>
#define MAXLEN 100
int main()
{
FILE *inputfile = NULL;
char name[MAXLEN];
int count;
Recall: Macro definition
16
File I/O (Input)
• Step 4a: Use fscanf() for input.
/* Assuming "names.lst" contains a
list of names, open this file for
reading. */
inputfile = fopen("names.lst", "r");
if (inputfile == NULL)
{
printf("Error opening names file.n");
return 1;
}
17
File I/O (Input)
• Step 4a: Use fscanf() for input.
/* Read in each name, and keep count how
many names there are in the file. */
count = 0;
while ( fscanf(inputfile, "%s", name) == 1 )
{
count++;
printf("%d %sn", count, name);
}
printf("nNumber of names read: %dn", count);
return 0;
}
18
File I/O (Input)
• Step 4a: Use fscanf() for input.
/* Read in each name, and keep count how
many names there are in the file. */
count = 0;
while ( fscanf(inputfile, "%s", name) == 1 )
{
count++;
printf("%d. %sn", count, name);
}
printf("nNumber of names read: %dn", count);
return 0;
}
Requires the file
handler (“stream”),
not the file name.
19
File I/O (Input)
• Step 4a: Use fscanf() for input.
/* Read in each name, and keep count how
many names there are in the file. */
count = 0;
while ( fscanf(inputfile, "%s", name) == 1 )
{
count++;
printf("%d. %sn", count, name);
}
printf("nNumber of names read: %dn", count);
return 0;
}
Other parameters:
like ordinary scanf().
20
File I/O (Input)
• Step 4a: Use fscanf() for input.
/* Read in each name, and keep count how
many names there are in the file. */
count = 0;
while ( fscanf(inputfile, "%s", name) == 1 )
{
count++;
printf("%d. %sn", count, name);
}
printf("nNumber of names read: %dn", count);
return 0;
}
fscanf() returns the number of
input items converted and
assigned successfully .
21
/* Read in each name, and keep count how
many names there are in the file. */
count = 0;
while ( fscanf(inputfile, "%s", name) == 1 )
{
count++;
printf("%d. %sn", count, name);
}
printf("nNumber of names read: %dn", count);
return 0;
}
File I/O (Input)
• Step 4a: Use fscanf() for input.
Used to check if a read or
assignment error occured, or end of
input file has been reached.
22
File I/O (Output)
• Step 4b: Use fprintf() for output.
#include <stdio.h>
#define MAXLEN 100
int main()
{
FILE *inputfile = NULL;
FILE *outfile = NULL;
char name[MAXLEN];
int count;
float mark;
/* Assuming "names.lst" contains a list of names,
open this file for reading. */
inputfile = fopen("names.lst", "r");
if (inputfile == NULL)
{
printf("Error opening names file.n");
return 1;
}
23
File I/O (Output)
• Step 4b: Use fprintf() for output.
/* The output file "names_marks.dat" will
contain the list of names and
corresponding marks. */
outfile = fopen("names_marks.dat", "w");
if (outfile == NULL)
{
printf("Error opening output file.n");
return 1;
}
24
File I/O (Output)
• Step 4b: Use fprintf() for output.
/* Read in each name, ask for the mark, and write name and mark to
output file. Also keep count how many names there are in the
file. */
count = 0;
while ( fscanf(inputfile, "%s", name ) == 1 )
{
count++;
printf("Enter mark for %s: ", name);
scanf("%f", &mark);
if ( fprintf(outfile, "%s %fn", name, mark) <= 0 )
{
printf("Error writing to output file.n");
return 1;
}
}
/*** etc ***/
25
File I/O (Output)
• Step 4b: Use fprintf() for output.
/* Read in each name, ask for the mark, and write name and mark to
output file. Also keep count how many names there are in the
file. */
count = 0;
while ( fscanf(inputfile, "%s", name ) == 1 )
{
count++;
printf("Enter mark for %s: ", name);
scanf("%f", &mark);
if ( fprintf(outfile, "%s %fn", name, mark) <= 0 )
{
printf("Error writing to output file.n");
return 1;
}
}
/*** etc ***/
File handler, not the
file name.
26
File I/O (Output)
• Step 4b: Use fprintf() for output.
/* Read in each name, ask for the mark, and write name and mark to
output file. Also keep count how many names there are in the
file. */
count = 0;
while ( fscanf(inputfile, "%s", name ) == 1 )
{
count++;
printf("Enter mark for %s: ", name);
scanf("%f", &mark);
if ( fprintf(outfile, "%s %fn", name, mark) <= 0 )
{
printf("Error writing to output file.n");
return 1;
}
}
/*** etc ***/
Other parameters:
like ordinary printf().
27
/* Read in each name, ask for the mark, and write name and mark to
output file. Also keep count how many names there are in the
file. */
count = 0;
while ( fscanf(inputfile, "%s", name ) == 1 )
{
count++;
printf("Enter mark for %s: ", name);
scanf("%f", &mark);
if ( fprintf(outfile, "%s %fn", name, mark) <= 0 )
{
printf("Error writing to output file.n");
return 1;
}
}
/*** etc ***/
File I/O (Output)
• Step 4b: Use fprintf() for output.
fprintf() returns the number of
characters written out
successfully, or negative if an
error occurs.
28
File I/O (Close)
• Step 5: Close file using fclose()
int main()
{
/*** etc ***/
printf("n");
printf("Number of names read: %dn", count);
fclose(inputfile);
fclose(outfile);
return 0;
}
29
File I/O (Close)
• Step 5: Close file using fclose()
int main()
{
/*** etc ***/
printf("n");
printf("Number of names read: %dn", count);
fclose(inputfile);
fclose(outfile);
return 0;
} File handler, not the
file name.
30
File I/O (Close)
• Step 5: Close file using fclose()
int main()
{
/*** etc ***/
printf("n");
printf("Number of names read: %dn", count);
fclose(inputfile);
fclose(outfile);
return 0;
}
• Clears input buffer.
• Flushes output buffer.
• fclose() fails when the
file was not opened
successfully.
31
Checking for EOF
• To check for end-of-file (or any other input
error), check that the number of items
converted and assigned successfully is
equal to the expected number of items.
while ( fscanf(inpf, "%s %f", name, &mark) == 2 )
{
printf("%st %fn", name, mark);
}
32
The rewind() Function
• You can use the rewind(stream)
function to re-set the file position at the start
of the input file again.
33
Test Program
#include <stdio.h>
#include <stdlib.h>
#include "countwords.h"
#include "countwords.c"
int main()
{
FILE *inputFile = NULL;
int count;
inputFile = openInput();
count = countWords(inputFile);
printf("nThere are %d words in the file.n", count);
rewind(inputFile);
count = countWords(inputFile);
printf("nThere are %d words in the file.n", count);
fclose(inputFile);
return 0;
}
Thank You
11/12/15

More Related Content

What's hot (20)

File in C language
File in C languageFile in C language
File in C language
 
File handling in c
File handling in cFile handling in c
File handling in c
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
File handling in C by Faixan
File handling in C by FaixanFile handling in C by Faixan
File handling in C by Faixan
 
File Management in C
File Management in CFile Management in C
File Management in C
 
File in C Programming
File in C ProgrammingFile in C Programming
File in C Programming
 
File handling-c
File handling-cFile handling-c
File handling-c
 
C programming file handling
C  programming file handlingC  programming file handling
C programming file handling
 
File handling in c
File handling in c File handling in c
File handling in c
 
File Management
File ManagementFile Management
File Management
 
File handling in c
File handling in cFile handling in c
File handling in c
 
File handling-dutt
File handling-duttFile handling-dutt
File handling-dutt
 
File handling in C
File handling in CFile handling in C
File handling in C
 
File Management in C
File Management in CFile Management in C
File Management in C
 
Files in C
Files in CFiles in C
Files in C
 
file
filefile
file
 
File Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CFile Handling and Command Line Arguments in C
File Handling and Command Line Arguments in C
 
File_Management_in_C
File_Management_in_CFile_Management_in_C
File_Management_in_C
 
File handling in c
File handling in cFile handling in c
File handling in c
 
file management in c language
file management in c languagefile management in c language
file management in c language
 

Viewers also liked

UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CAshim Lamichhane
 
file handling c++
file handling c++file handling c++
file handling c++Guddu Spy
 
File Management Presentation
File Management PresentationFile Management Presentation
File Management PresentationSgtMasterGunz
 
File management ppt
File management pptFile management ppt
File management pptmarotti
 

Viewers also liked (7)

UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in C
 
file handling c++
file handling c++file handling c++
file handling c++
 
File Management Presentation
File Management PresentationFile Management Presentation
File Management Presentation
 
File Management
File ManagementFile Management
File Management
 
File management
File managementFile management
File management
 
File management ppt
File management pptFile management ppt
File management ppt
 
File Management
File ManagementFile Management
File Management
 

Similar to File handling in c

Similar to File handling in c (20)

file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
File Handling in C Programming for Beginners
File Handling in C Programming for BeginnersFile Handling in C Programming for Beginners
File Handling in C Programming for Beginners
 
Unit5
Unit5Unit5
Unit5
 
File management
File managementFile management
File management
 
C-Programming File-handling-C.pptx
C-Programming  File-handling-C.pptxC-Programming  File-handling-C.pptx
C-Programming File-handling-C.pptx
 
C-Programming File-handling-C.pptx
C-Programming  File-handling-C.pptxC-Programming  File-handling-C.pptx
C-Programming File-handling-C.pptx
 
Lecture 20 - File Handling
Lecture 20 - File HandlingLecture 20 - File Handling
Lecture 20 - File Handling
 
Files in c
Files in cFiles in c
Files in c
 
file.ppt
file.pptfile.ppt
file.ppt
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Satz1
Satz1Satz1
Satz1
 
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYC UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
 
File management
File managementFile management
File management
 
14. fiile io
14. fiile io14. fiile io
14. fiile io
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operations
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 

More from thirumalaikumar3 (8)

Data type in c
Data type in cData type in c
Data type in c
 
Control flow in c
Control flow in cControl flow in c
Control flow in c
 
C function
C functionC function
C function
 
Coper in C
Coper in CCoper in C
Coper in C
 
C basics
C   basicsC   basics
C basics
 
Structure c
Structure cStructure c
Structure c
 
String c
String cString c
String c
 
Data type2 c
Data type2 cData type2 c
Data type2 c
 

Recently uploaded

4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsPooky Knightsmith
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvRicaMaeCastro1
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxDhatriParmar
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 

Recently uploaded (20)

4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young minds
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 

File handling in c

  • 1. 1 Topics • File Handling in C • Basic File I/O Functions • Example
  • 2. 11/12/15 File File – place on disk where group of related data is stored E.g. your C programs, executables High-level programming languages support file operations Naming Opening Reading Writing Closing
  • 3. 3 File Handling in C • Files need to be opened before use. – Associate a "file handler" to each file – Modes: read, write, or append • File I/O functions use the file handler (not the filename). • Need to close the file after use. • Basic file handling functions: fopen(), fclose(), fscanf(), fprintf().
  • 4. 4 File I/O Example • Write a program which: – inputs a list of names from a file called names.lst – counts the number of names in the list – asks a mark for each name in the file – outputs the name and corresponding mark to the file names_marks.dat • Note: the tasks above are not necessarily accomplished in that order.
  • 5. 5 File I/O (Header) • Step 0: Include stdio.h. #include <stdio.h> int main() { ... return 0; }
  • 6. 6 File I/O (File Pointer) • Step 1: Declare a file handler (i.e. file pointer) as FILE * for each file. int main() { FILE *inputfile = NULL; FILE *outputfile = NULL; FILE *currentfile = NULL; ... return 0; }
  • 7. 7 File I/O (Open) • Step 2: Open file using fopen(). int main() { FILE *inputfile = NULL; FILE *outputfile = NULL; FILE *currentfile = NULL; inputfile = fopen(“Names.txt”, “r”); outputfile = fopen(“marks.dat”, “w”); currentfile = fopen(“logFile.txt”, “a”); ... return 0; }
  • 8. 8 File I/O (Open) • Step 2: Open file using fopen(). int main() { FILE *inputfile = NULL; FILE *outputfile = NULL; FILE *currentfile = NULL; inputfile = fopen(“Names.txt”, “r”); outputfile = fopen(“marks.dat”, “w”); currentfile = fopen(“logFile.txt”, “a”); ... return 0; } File name
  • 9. 9 File I/O (Open) • Step 2: Open file using fopen(). int main() { FILE *inputfile = NULL; FILE *outputfile = NULL; FILE *currentfile = NULL; inputfile = fopen(“Names.txt”, “r”); outputfile = fopen(“marks.dat”, “w”); currentfile = fopen(“logFile.txt”, “a”); ... return 0; } Mode r : read w : write a : append Warning: The "w" mode overwrites the file, if it exists.
  • 10. 10 File I/O (Open) • Step 2: Open file using fopen(). int main() { FILE *inputfile = NULL; FILE *outputfile = NULL; FILE *currentfile = NULL; inputfile = fopen(“Names.txt”, “r”); outputfile = fopen(“marks.dat”, “w”); currentfile = fopen(“logFile.txt”, “a”); ... return 0; } Associate a file handler for every file to be used.
  • 11. 11 File I/O (Error Check) • Step 3: Check if file is opened successfully. int main() { FILE *inputfile; inputfile = fopen(“Names.txt”, “r”); if (inputfile == NULL) { printf(“Unable to open input file.n”); return 1; } ... return 0; }
  • 12. 12 File I/O (Error Check) • Step 3: Check if file is opened successfully. int main() { FILE *inputfile; inputfile = fopen(“Names.txt”, “r”); if (inputfile == NULL) { printf(“Unable to open input file.n”); return 1; } ... return 0; } File handler becomes NULL when an fopen() error occurs.
  • 13. 13 File I/O (Error Check) • Step 3: Check if file is opened successfully. int main() { FILE *inputfile; inputfile = fopen(“Names.txt”, “r”); if (inputfile == NULL) { printf(“Unable to open input file.n”); return 1; } ... return 0; } Ends program if inside main ( ) function.
  • 14. 14 File I/O (Input) • Step 4a: Use fscanf() for input. #include <stdio.h> #define MAXLEN 100 int main() { FILE *inputfile = NULL; char name[MAXLEN]; int count;
  • 15. 15 File I/O (Input) • Step 4a: Use fscanf() for input. #include <stdio.h> #define MAXLEN 100 int main() { FILE *inputfile = NULL; char name[MAXLEN]; int count; Recall: Macro definition
  • 16. 16 File I/O (Input) • Step 4a: Use fscanf() for input. /* Assuming "names.lst" contains a list of names, open this file for reading. */ inputfile = fopen("names.lst", "r"); if (inputfile == NULL) { printf("Error opening names file.n"); return 1; }
  • 17. 17 File I/O (Input) • Step 4a: Use fscanf() for input. /* Read in each name, and keep count how many names there are in the file. */ count = 0; while ( fscanf(inputfile, "%s", name) == 1 ) { count++; printf("%d %sn", count, name); } printf("nNumber of names read: %dn", count); return 0; }
  • 18. 18 File I/O (Input) • Step 4a: Use fscanf() for input. /* Read in each name, and keep count how many names there are in the file. */ count = 0; while ( fscanf(inputfile, "%s", name) == 1 ) { count++; printf("%d. %sn", count, name); } printf("nNumber of names read: %dn", count); return 0; } Requires the file handler (“stream”), not the file name.
  • 19. 19 File I/O (Input) • Step 4a: Use fscanf() for input. /* Read in each name, and keep count how many names there are in the file. */ count = 0; while ( fscanf(inputfile, "%s", name) == 1 ) { count++; printf("%d. %sn", count, name); } printf("nNumber of names read: %dn", count); return 0; } Other parameters: like ordinary scanf().
  • 20. 20 File I/O (Input) • Step 4a: Use fscanf() for input. /* Read in each name, and keep count how many names there are in the file. */ count = 0; while ( fscanf(inputfile, "%s", name) == 1 ) { count++; printf("%d. %sn", count, name); } printf("nNumber of names read: %dn", count); return 0; } fscanf() returns the number of input items converted and assigned successfully .
  • 21. 21 /* Read in each name, and keep count how many names there are in the file. */ count = 0; while ( fscanf(inputfile, "%s", name) == 1 ) { count++; printf("%d. %sn", count, name); } printf("nNumber of names read: %dn", count); return 0; } File I/O (Input) • Step 4a: Use fscanf() for input. Used to check if a read or assignment error occured, or end of input file has been reached.
  • 22. 22 File I/O (Output) • Step 4b: Use fprintf() for output. #include <stdio.h> #define MAXLEN 100 int main() { FILE *inputfile = NULL; FILE *outfile = NULL; char name[MAXLEN]; int count; float mark; /* Assuming "names.lst" contains a list of names, open this file for reading. */ inputfile = fopen("names.lst", "r"); if (inputfile == NULL) { printf("Error opening names file.n"); return 1; }
  • 23. 23 File I/O (Output) • Step 4b: Use fprintf() for output. /* The output file "names_marks.dat" will contain the list of names and corresponding marks. */ outfile = fopen("names_marks.dat", "w"); if (outfile == NULL) { printf("Error opening output file.n"); return 1; }
  • 24. 24 File I/O (Output) • Step 4b: Use fprintf() for output. /* Read in each name, ask for the mark, and write name and mark to output file. Also keep count how many names there are in the file. */ count = 0; while ( fscanf(inputfile, "%s", name ) == 1 ) { count++; printf("Enter mark for %s: ", name); scanf("%f", &mark); if ( fprintf(outfile, "%s %fn", name, mark) <= 0 ) { printf("Error writing to output file.n"); return 1; } } /*** etc ***/
  • 25. 25 File I/O (Output) • Step 4b: Use fprintf() for output. /* Read in each name, ask for the mark, and write name and mark to output file. Also keep count how many names there are in the file. */ count = 0; while ( fscanf(inputfile, "%s", name ) == 1 ) { count++; printf("Enter mark for %s: ", name); scanf("%f", &mark); if ( fprintf(outfile, "%s %fn", name, mark) <= 0 ) { printf("Error writing to output file.n"); return 1; } } /*** etc ***/ File handler, not the file name.
  • 26. 26 File I/O (Output) • Step 4b: Use fprintf() for output. /* Read in each name, ask for the mark, and write name and mark to output file. Also keep count how many names there are in the file. */ count = 0; while ( fscanf(inputfile, "%s", name ) == 1 ) { count++; printf("Enter mark for %s: ", name); scanf("%f", &mark); if ( fprintf(outfile, "%s %fn", name, mark) <= 0 ) { printf("Error writing to output file.n"); return 1; } } /*** etc ***/ Other parameters: like ordinary printf().
  • 27. 27 /* Read in each name, ask for the mark, and write name and mark to output file. Also keep count how many names there are in the file. */ count = 0; while ( fscanf(inputfile, "%s", name ) == 1 ) { count++; printf("Enter mark for %s: ", name); scanf("%f", &mark); if ( fprintf(outfile, "%s %fn", name, mark) <= 0 ) { printf("Error writing to output file.n"); return 1; } } /*** etc ***/ File I/O (Output) • Step 4b: Use fprintf() for output. fprintf() returns the number of characters written out successfully, or negative if an error occurs.
  • 28. 28 File I/O (Close) • Step 5: Close file using fclose() int main() { /*** etc ***/ printf("n"); printf("Number of names read: %dn", count); fclose(inputfile); fclose(outfile); return 0; }
  • 29. 29 File I/O (Close) • Step 5: Close file using fclose() int main() { /*** etc ***/ printf("n"); printf("Number of names read: %dn", count); fclose(inputfile); fclose(outfile); return 0; } File handler, not the file name.
  • 30. 30 File I/O (Close) • Step 5: Close file using fclose() int main() { /*** etc ***/ printf("n"); printf("Number of names read: %dn", count); fclose(inputfile); fclose(outfile); return 0; } • Clears input buffer. • Flushes output buffer. • fclose() fails when the file was not opened successfully.
  • 31. 31 Checking for EOF • To check for end-of-file (or any other input error), check that the number of items converted and assigned successfully is equal to the expected number of items. while ( fscanf(inpf, "%s %f", name, &mark) == 2 ) { printf("%st %fn", name, mark); }
  • 32. 32 The rewind() Function • You can use the rewind(stream) function to re-set the file position at the start of the input file again.
  • 33. 33 Test Program #include <stdio.h> #include <stdlib.h> #include "countwords.h" #include "countwords.c" int main() { FILE *inputFile = NULL; int count; inputFile = openInput(); count = countWords(inputFile); printf("nThere are %d words in the file.n", count); rewind(inputFile); count = countWords(inputFile); printf("nThere are %d words in the file.n", count); fclose(inputFile); return 0; }