Show Menu
Cheatography

C program Cheat Sheet by

C Syntax, Data Types, Structure & Common Library Functions

Console Input/­Output

#include <st­dio.h>
Character
getchars{}
Returns a single charac­ter's ANSI code from the input stream buffer as an integer. (safe)
putcha­r(int)
Prints a single character from an ANSI code integer to the output stream buffer.
Strings
gets(s­trName)
Reads a line from the input stream into a string variable. (Unsafe, removed in C11.)
Altern­ative
fgets(­str­Name, length, stdin);
Reads a line from the input stream into a string variable. (Safe)
puts("s­tri­ng")
Prints a string to the output stream.
Formatted Data
scanf(­"­%d", &x)
Read value/s (type defined by format string) into variable/s (type must match) from the input stream. Stops reading at the first whites­pace. & prefix not required for arrays (including strings.) (unsafe)
printf­­("I love %c %d!", 'C', 99)
Prints data (formats defined by the format string) as a string to the output stream.
Altern­ative
fgets(­str­Name, length, stdin); sscanf­(st­rName, "­%d", &x);
Uses fgets to limit the input length, then uses sscanf to read the resulting string in place of scanf. (safe)

Dynamic Memory

Remember to #include <st­dio.h>
Allocate
malloc
ptr = malloc(n sizeof ptr);
calloc
ptr = calloc(n, sizeof *ptr);
Change Size
realloc
newsize = n sizeof ptr; tmp = reallo­­c(ptr, newsize); if (tmp) ptr = tmp; else / ptr is still valid /;
Release
free
free(ptr);

Escape Character

\a
alarm (bell/­beep)
\b
backspace
\f
formfeed
\n
newline
\r
carriage return
\t
horizontal tab
\v
vertical tab
\\
backslash
\'
single quote
\"
double quote
\?
question mark
\nnn
Any octal ANSI character code.
\xhh
Any hexade­cimal ANSI character code.

Data type

Character
char
1 byte
-128 to 127
 
unsigned char
1 byte
0 to 255
Integer
int
4 byte
-32,767 to 32,767
 
unsigned int
4 byte
0 to 65,535
 
short int
2 byte
-32,767 to 32,767
 
unsigned short int
2 byte
0 to 65,535
 
long int
4 byte
-2,147­,48­3,647 to 2,147,­483,647
 
unsigned long int
4 byte
0 to 4,294,­967,295
 
long long int
8 byte
-(263 – 1) to 263 – 1 (It will be added by the C99 standard)
 
unsigned long long int
8 byte
264 – 1 (It will be added by the C99 standard)
Float
float
4 byte
1E-37 to 1E+37 along with six digits of the precisions here
 
double
8 byte
1E-37 to 1E+37 along with six digits of the precisions here
 
long double
8 byte
1E-37 to 1E+37 along with six digits of the precisions here

File Input/­­Output

#include <st­dio.h>
Opening
FILE *fptr = fopen(­fil­ename, mode);
FILE *fptr
Declares fptr as a FILE type pointer (stores stream location instead of memory location.)
fopen()
Returns a stream location pointer if succes­sful, 0 otherwise.
filename
String containing file's directory path & name.
mode
String specifying the file access mode.
Modes
"­r" / "­rb"
Read existing text/b­inary file.
"­w" / "­wb"
Write new/over existing text/b­inary file.
"­a" / "­ab"
Write new/append to existing text/b­inary file.
"­r+" / "­r+b­" / "­rb+­"
Read and write existing text/b­inary file.
"­w+" / "­w+b­" / "­wb+­"
Read and write new/over existing text/b­inary file.
"­a+" / "­a+b­" / "­ab+­"
Read and write new/append to existing text/b­inary file.
Closing
fclose­(fptr);
Flushes buffers and closes stream. Returns 0 if succes­sful, EOF otherwise.
Random Access
ftell(­fptr)
Return current file position as a long integer.
fseek(­fptr, offset, origin);
Sets current file position. Returns false is succes­sful, true otherwise. The offset is a long integer type.
Origins
SEEK_SET
Beginning of file.
SEEK_CUR
Current position in file.
SEEK_END
End of file.
Utilities
feof(fptr)
Tests end-of­-file indicator.
rename­(st­rOl­dName, strNew­Name)
Renames a file.
remove­(st­rName)
Deletes a file.
Characters
fgetc(­fptr)
Returns character read or EOF if unsucc­­es­sful. (safe)
fputc(int c, fptr)
Returns character written or EOF if unsucc­­es­sful.
Strings
fgets(char *s, int n, fptr)
Reads n-1 characters from file fptr into string s. Stops at EOF and \n. (safe)
fputs(char *s, fptr)
Writes string s to file fptr. Returns non-ne­­gative on success, EOF otherwise.
Formatted Data
fscanf­(fptr, format, [...])
Same as scanf with additional file pointer parameter. (unsafe)
fprint­f(fptr, format, [...])
Same as printf with additional file pointer parameter.
Altern­ative
fgets(­str­Name, length, fptr); sscanf­(st­rName, "­%d", &x);
Uses fgets to limit the input length, then uses sscanf to read the resulting string in place of scanf. (safe)
Binary
fread(void *ptr, sizeof­(el­ement), number, fptr)
Reads a number of elements from fptr to array *ptr. (safe)
fwrite­(void *ptr, sizeof­(el­ement), number, fptr)
Writes a number of elements to file fptr from array *ptr.
 

Variabels

Declaring
int x;
A variable.
char x = 'C';
A variable & initia­lising it.
float x, y, z;
Multiple variables of the same type.
const int x = 88;
A constant variable: can't assign to after declar­­ation (compiler enforced.)
Naming
johnny­5Is­Alive
Alphan­umeric, not a keyword, begins with a letter.
2001AS­pac­eOd­dysey X
Doesn't begin with a letter.
while X
Reserved keyword.
how exciting! X
Non-al­pha­num­eric.
iamave­­ry­l­o­ng­­var­­ia­b­l­en­­ame­­oh­m­y­go­­shy­­esiam X
Longer than 31 characters (C89 & C90 only)

Input Format

Specifier
Input Text is a
Destin­ation type
%c
Character
Char
%d
Decimal
Int, short
%x
Hexade­cimal
Int, short, long
%ld
Long Decimal
Long
%lld
Very Long Decimal
Long Long
%f
Floati­ng-­point
Float
%lf
Floati­ng-­point
Double
%le
Expone­ntial
Double

Read file line-b­y-line

#include <st­­di­o.h>

FILE h;
char line[100];
h = fopen(­­"­f­il­­ena­­me­", "­­rb­");
/
error checking missing /
while (fgets­­(line, sizeof line, h)) {
­ ­ ­ /
deal with line /
}
/
if needed test why last read failed /
if (feof(h) || ferror(h)) /
whatever */;
fclose(h);

main()

int main(int argc, char *argv[­]){­return int;}
Anatomy
int main
Program entry point.
int arcg
# of command line arguments.
char *argv[]
Command line arguments in an array of strings. #1 is always the program filename.
return int;
Exit status (integer) returned to the OS upon program exit.
Command Line Arguments
app two 3
Three arguments, "­­ap­p­", "­­tw­o­" and "­­3".
app "two 3"
Two arguments, "­­ap­p­" and "two 3".
main is the first function called when the program executes.

Placeh­­older Types (f/printf And f/scanf)

printf("%d%d...", arg1, arg2...);
Type
Example
Descri­ption
%d or %I
-42
Signed decimal integer.
%u
42
Unsigned decimal integer.
%o
52
Unsigned octal integer.
%x or %X
2a or 2A
Unsigned hexade­cimal integer.
%f or %F
1.21
Signed decimal float.
%e or %E
1.21e+9 or 1.21E+9
Signed decimal w/ scientific notation.
%g or %G
1.21e+9 or 1.21E+9
Shortest repres­ent­ation of %f/%F or %e/%E.
%a or %A
0x1.20­7c8­ap+30 or 0X1.20­7C8­AP+30
Signed hexade­cimal float.
%c
a
A character.
%s
A string.
A character string.
%p
 
A pointer
%%
&
A percent character.
%n
No output, saves # of characters printed so far. Respective printf argument must be an integer pointer.

Comments

// We're single­-line comments!
//Nothing compiled after // on these lines.

/* I'm a multi-line comment!
Nothing compiled between
these delimi­ters. */

Escape Characters

\a
alarm (bell/­beep)
\f
formfeed
\r
carriage return
\v
vertical tab
\'
single quote
\?
question mark
\nnn
Any octal ANSI character code.
\xhh
Any hexade­cimal ANSI character code.
\b
backspace
\n
newline
\t
horizontal tab
\\
backslash
\"
double quote

Strings

'A'
character
Single quotes.
"­AB"
string
Double quotes.
\0
Null termin­­ator.
Strings are
char
arrays.
char name[4] = "­Ash­";
is equivalent to
char name[4] = {'A', 's', 'h', '\0'}; 
int i; for(i = 0; name[i]; i++){} 
\0
evaluates as false.
Strings must include a
char
element for
\0.
       
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          C Reference Cheat Sheet
          C# CheatSheet Cheat Sheet