SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances (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
 

En vedette

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
 

En vedette (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
 

Similaire à File handling in c

Similaire à 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
 

Plus de 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
 

Dernier

Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
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
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinojohnmickonozaleda
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 

Dernier (20)

FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
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
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipino
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 

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; }