Lecture 5 - Input/Output Flashcards
What is stream-based I/O in C?
C provides an extensive library for stream-based I/O, which allows reading/writing from/to the console, file system, or memory buffers. It supports both text files (divided into lines) and binary files (sequences of bytes), with sequential or direct access.
What is the purpose of the fopen
function in C?
fope
opens a file and returns a pointer to a file descriptor. If it fails, it returns NULL
. The first argument is the filename, and the second is the mode, which can be “r” (read), “w” (write), “a” (append), etc.
What does the function fprintf
do?
fprintf
writes formatted output to a specified stream. It is similar to printf
but allows output to be directed to a specific file or stream, e.g., fprintf(stderr, "Error message");
.
How does buffering work in C I/O?
Streams are automatically buffered for efficiency. The buffer can be flushed using fflush
, and fclose
flushes the buffer before closing the stream. The buffering can be modified using setvbuf
.
What are the basic access modes for fopen
?
The common access modes are:
"r"
: Open an existing file for input."w"
: Create a new file or truncate an existing one for output."a"
: Append to an existing file or create a new file for output.
What is the use of fflush
in C?
fflush
flushes the output buffer of a stream, forcing the written data to be sent to the destination, which is useful for ensuring that all data is written to a file before the file is closed.
What is the EOF
constant used for in C?
EOF
(End of File) is a constant used to indicate the end of a file or an error when performing input/output operations, such as in a while
loop that reads characters until EOF
is reached.
What is the difference between printf
and fprintf
?
printf
outputs to the standard output (typically the console), while fprintf
can output to a specified file or stream, allowing formatted output to destinations other than the console.
How can you open a file for both reading and writing in C?
Use the mode "r+"
for opening an existing file for both reading and writing, or "w+"
for creating a new file or truncating an existing one for update.
What function is used to close a file in C, and why is it important?
fclose
is used to close a file, ensuring that any data still in the buffer is written to the file and that resources associated with the file are released.