Unit 8
Unit 8
PROBLEM SOLVING
(BE01000121)
CHAPTER-10
FILE MANAGEMENT
ROADMAP
File Operations: Opening, closing, reading, writing
files.
Example: fp = fopen("printfile.c","r");
fclose(filepoin Closes a file and release the pointer.
ter);
Example: fclose(fp);
fprintf(fp, Here fp is a file pointer associated with a file. The
“control string control string contains items to be printed. The list
”, list); may includes variables, constants and strings.
Example:
fprintf(fp, "%s %d %c", name, age, gender);
FILE-HANDLING FUNCTIONS
Syntax Description
fscanf(fp, Here fp is a file pointer associated with a file. The
“control strin control string contains items to be printed. The list may
g”, includes variables, constants and strings.
list);
Example: fscanf(fp, "%s %d", &item, &qty);
int getc( getc() returns the next character from a file referred by
FILE *fp); fp; it require the FILE pointer to tell from which file. It
returns EOF for end of file or error.
Example: c = getc(fp);
int putc(int c putc() writes or appends the character c to the FILE fp. If
, a putc function is successful, it returns the character
FILE *fp); written, EOF if an error occurs.
Example: i = getw(fp);
putw(int,
FILE *fp); putw writes an integer value read from terminal and are
written to the FILE using fp.
EOF
EOF stands for “End of File”. EOF is an integer defined in
<stdio.h>
Open the file for reading only. If it exists, then the file is
r
opened with the current contents; otherwise an error occurs.
Open the file for writing only. A file with specified name is
w created if the file does not exists. The contents are deleted, if
the file already exists.
Open the file for appending (or adding data at the end of file)
data to it. The file is opened with the current contents safe. A
a
file with the specified name is created if the file does not
exists.
The existing file is opened to the beginning for both reading
r+
and writing.
w+ Same as w except both for reading and writing.
a+ Same as a except both for reading and writing.
FILE OPENING MODES
• S
FILE POSITIONING FUNCTIONS
• fseek, ftell, and rewind functions will set the file pointer to
new location.
• A subsequent read or write will access data from the new
position.
Syntax Description
fseek(FILE *fp, fseek() function is used to move the file position to
a desired location within the file. fp is a FILE
long offset, pointer, offset is a value of datatype long, and
int position); position is an integer number.
rewind(fp);
WRITE A C PROGRAM TO COUNT LINES, WORDS,
TABS, AND CHARACTERS
• S