Files and Streams Flashcards
(47 cards)
What does the scanf() function do?
It’s the reverse of printf() - used for formatted input from the console.
What does the return value of scanf() represent?
The number of data items successfully assigned a value.
What’s the correct way to read an integer using scanf()?
scanf(“%d”, &k) - The ampersand before the variable name is required to pass by reference.
What is a stream in C?
An abstraction of a file that provides a consistent interface to the programmer, regardless of the actual device.
What are two key characteristics of streams?
Streams are buffered, and may be text or binary.
What’s the difference between text and binary streams?
Text streams are sequences of characters with possible character translation (e.g., newline → CR+LF), while binary streams are sequences of bytes with no character translation.
What header file is required to use stream functions?
<stdio.h>
</stdio.h>
What is the purpose of a file pointer?
A file pointer (FILE *) is used to identify and manage a stream for file operations.
How do you open a file in C?
Using fopen(): FILE *fp = fopen(“filename”, “mode”);
Why should you always check if a file was opened successfully?
Because fopen() returns NULL if it fails to open the file.
What is the correct pattern to check if a file opened successfully?
if ((fp = fopen(“filename”, “r”)) == NULL) {
/* error handling */
}
How do you close a file in C?
Using fclose(fp);
What does the “r” mode do when opening a file?
Opens a text file for reading from
Q: What does the “w” mode do when opening a file?
Creates a text file for writing to (overwrites if file exists).
What does the “a” mode do when opening a file?
Opens a text file for appending to (writing to the end of it).
What’s the difference between “r+” and “w+”?
“r+” opens an existing file for both reading and writing, while “w+” creates a new file (or truncates existing) for both reading and writing.
How do you specify a binary file mode?
By adding “b” to the mode, e.g., “rb”, “wb”, “ab”.
What is errno
in C?
A global variable defined in errno.h
that is updated by system functions when an error occurs.
How can you get the text description of an error based on errno?
Using strerror(errno)
from <string.h>
What does the ferror()
function do?
Determines whether the most recent operation on a file produced an error.
When is the value of ferror()
reset?
It’s reset by each file operation.
What function writes a single character to a stream?
fputc(ch, fp)
What function writes a string to a stream?
fputs(str, fp)
Does fputs()
output the null terminator?
No, the null terminator is not output.