C Reference Cheat Sheet Page 7

ADVERTISEMENT

C Reference Cheat Sheet
by
Ashlyn Black
via
Console Input/​ O utput (cont)
File Input/​ O utput
Reads a line from the input stream into a string
gets(strName)
#include <stdio.h>
variable. (Unsafe, removed in C11.)
Opening
Alternative
FILE *fptr = fopen(filename, mode);
Reads a line from the input stream into a string
fgets(strName,
Declares fptr as a FILE type pointer (stores stream
FILE *fptr
variable. (Safe)
length, stdin);
location instead of memory location.)
Prints a string to the output stream.
puts("string")
Returns a stream location pointer if successful, 0
fopen()
Formatted Data
otherwise.
Read value/s (type defined by format string) into
String containing file's directory path & name.
scanf("%d", &x)
filename
variable/s (type must match) from the input stream.
String specifying the file access mode.
mode
Stops reading at the first whitespace. & prefix not
Modes
required for arrays (including strings.) (unsafe)
"r" / "rb"
Read existing text/binary file.
Prints data (formats defined by the format string) as
print​ f ("I love
a string to the output stream.
%c %d!", 'C',
"w" / "wb"
Write new/over existing text/binary file.
99)
"a" / "ab"
Write new/append to existing text/binary file.
Alternative
"r+" / "r+b" /
Read and write existing text/binary file.
Uses fgets to limit the input length, then uses
fgets(strName,
"rb+"
sscanf to read the resulting string in place of
length, stdin);
"w+" / "w+b" /
Read and write new/over existing text/binary file.
scanf. (safe)
sscanf(strName,
"wb+"
"%d", &x);
"a+" / "a+b" /
Read and write new/append to existing text/binary
The stream buffers must be flushed to reflect changes. String terminator
file.
"ab+"
characters can flush the output while newline characters can flush the
input.
Closing
Flushes buffers and closes stream. Returns 0 if
fclose(fptr);
Safe functions are those that let you specify the length of the input. Unsafe
successful, EOF otherwise.
functions do not, and carry the risk of memory overflow.
Random Access
Return current file position as a long integer.
ftell(fptr)
By Ashlyn Black
Published 28th January, 2015.
Sponsored by
Last updated 20th April, 2015.
Measure your website readability!
Page 7 of 13.

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education