File I/O (Input/Output)
File I/O (Input/Output) in C. This allows you to read from and write to files, which is essential for many applications.
File I/O in C
Opening and Closing Files
To work with files, you first need to open them using the fopen
function and close them with fclose
.
Syntax for fopen
:
filename
: Name of the file.mode
: File access mode (e.g.,"r"
for reading,"w"
for writing).
Syntax for fclose
:
stream
: Pointer to theFILE
object.
Example: Opening and Closing Files
Reading from Files
To read data from a file, use functions like fscanf
, fgets
, and fread
.
Syntax for fscanf
:
stream
: Pointer to theFILE
object.format
: Format string similar toprintf
.
Syntax for fgets
:
str
: Buffer to store the string.n
: Maximum number of characters to read.stream
: Pointer to theFILE
object.
Syntax for fread
:
ptr
: Pointer to the memory where data will be read.size
: Size of each item to read.count
: Number of items to read.stream
: Pointer to theFILE
object.
Example: Reading from a File
Writing to Files
To write data to a file, use functions like fprintf
, fputs
, and fwrite
.
Syntax for fprintf
:
stream
: Pointer to theFILE
object.format
: Format string similar toprintf
.
Syntax for fputs
:
str
: String to write.stream
: Pointer to theFILE
object.
Syntax for fwrite
:
ptr
: Pointer to the data to write.size
: Size of each item to write.count
: Number of items to write.stream
: Pointer to theFILE
object.
Example: Writing to a File
Error Handling
Error handling is crucial for robust file operations. Use ferror
and clearerr
to check and clear errors.
Syntax for ferror
:
stream
: Pointer to theFILE
object.
Syntax for clearerr
:
stream
: Pointer to theFILE
object.
Example: Error Handling
Explanation:
perror
: Prints a descriptive error message based on the current value oferrno
.ferror
: Checks if an error occurred on the file stream.clearerr
: Clears the error indicators for the file stream.
Summary
Opening and Closing Files: Use
fopen
andfclose
.Reading Files: Use
fscanf
,fgets
, andfread
.Writing Files: Use
fprintf
,fputs
, andfwrite
.Error Handling: Use
ferror
,clearerr
, andperror
to handle and report errors.
Last updated
Was this helpful?