C Cheat Sheet Flashcards
FILE *fopen(const char *path, const char *mode);
Description: Opens the file specified by path with the access mode specified in mode. The mode can be:
- “r”: Open for reading.
- “w”: Open for writing (creates a new file or truncates an existing file).
- “a”: Open for appending (creates a new file if it does not exist).
- Modes can also include + to allow both reading and writing, like “r+” or “w+”.
Returns:
- Success: A pointer to a FILE object that can be used to operate on the file.
- Failure: NULL, typically if the file cannot be opened (e.g., if the file doesn’t exist when using “r”, or if there are insufficient permissions).
Example:
FILE *file = fopen(“example.txt”, “r”);
int fclose(FILE *fp);
Return Value:
- 0: Indicates that the file was closed successfully.
- EOF (typically -1): Indicates an error occurred during the closing process.
int printf(const char *format, …);
Parameters:
- const char *format: A format string that specifies how the following arguments should be printed. The format string can contain text and format specifiers (such as %d, %s, %f, etc.) for different types.
Return Value:
- Returns an integer: The number of characters printed (excluding the null byte \0 at the end of strings).
- Returns a negative value: Indicates an error occurred during printing.
int fprintf(FILE *stream, const char *format, …);
Parameters:
- FILE *stream: A pointer to the file where you want to write the output. This can be a file opened with fopen, or standard streams like stdout (for console output) or stderr (for error messages).
- const char *format: A format string that specifies how to format the output. It can include text and format specifiers (e.g., %d for integers, %s for strings, %f for floating-point numbers, etc.).
- … (ellipsis): The variable arguments corresponding to each format specifier in the format string.
Return Value:
- Returns an integer: The total number of characters written, excluding the null terminator (\0).
- Returns a negative value: Indicates that an error occurred while writing to the stream.
int scanf(const char *format, …);
Parameters:
- const char *format: A format string that specifies how to interpret the input. The format string can include format specifiers (such as %d, %s, %f, etc.) to indicate the expected types of input data.
- … (ellipsis): A variable number of pointers to variables where the read values will be stored. Each format specifier in the format string corresponds to one argument, and these arguments must be pointers (e.g., int *, float *, char *) so that scanf can modify the variables at those addresses.
Return Value:
- Returns an integer: The number of items successfully read and assigned.
- Returns EOF (usually -1): Indicates an input failure or that the end of the input stream has been reached.
int fscanf(FILE *stream, const char *format, …);
Same as scanf, but with a FILE*