I/O Functions
See the list of functions on this reference website.
Standard input/output
We must #include <stdio.h> to use this library. The standard
(built-in) streams are defined there:
stdin: keyboard or input redirect inputstdout: standard output (to console by default)stderr: standard error output (to console by default)
Output in C
Prerequisite: #include <stdio.h> in header to access library functions; Reference for stdio.h
-
putchar('d')to output characters -
puts("some string")to output strings -
printf("format string", args...)for fancier output - formats:
%i %d %f %c %s %n %ld %lffor basic types
%ooctal printing of ints
%xhex printing of ints - field widths
%cols.decf- eg.%.2f,%.6f
right justified by default, use%-to left justify
-and cols works for %d and %s also - See Kernighan Appendix B or this reference for details
Input in C
Character-based Input
-
stdiofunctiongetchar()reads one character from a file - Returns
EOFif at end of file - Value of
EOFis -1
getchar()returns aninttype for this reason (automatically cast tocharif needed) - Type ctrl-d in a Unix system to produce an
EOFfrom keyboard (ctrl-Z (Enter) on a PC)
Formatted Input
- The
scanffunction works similarly to the printf output function for reading formatted input. - We use a format
string followed by the
memory locations (addresses) we are reading into. - We indicate this for most variables by preceding the
variable name with an ampersand character (
&) to indicate "address of" the variable. - An exception is strings because they are arrays, and as we'll learn soon, array names are the memory address where the array starts. </p>
%d integer
%ld long
%c char
%s string
%f float (real number type)
%lf double, Lf long double
There are also many fancy input format options, see scanf documentation for details:
- Scan set notation:
%[a-zA-Z]- inputs as long as chars in set,[^0-9]is "all except" inverse - Use character literals to requre but skip over them, eg
%d-%d-%dwould successfully read2-3-4 - Use
%*cto skip any character (*skips assigning any value)
Here is a short example: ```c #include <stdio.h> int main() { int number; float x; double y; char word[20]; scanf("%d", &number); scanf("%f %lf", &x, &y); scanf("%s", word); } ```
Note that we don't need & in front of word because
as an array it is an address already. We also don't use a
subscript since we're reading into the whole array. When
reading a string, scanf only reads up to first whitespace
(space, tab, ret).
Sequential Files
- Declare as:
FILE *fptr;(FILEis the type of files, defined in<stdio.h>) - Must open file for use, giving it pointer, name, and mode
fptr = fopen("name.txt", "w")(returns NULL if error) - types of file openings:
-
"r"- reading -
"w"- create or overwrite file for writing -
"a"- open or create file for appending to end -
"r+"- open for update (read and/or write) -
"w+"- create (overwrite) file for read &/or write -
"a+"- open for read or write to end
-
- Close a file when done:
fclose(fptr);- very important to permanently save file! - Test for end of file:
feof(fptr)returns 1 if end, 0 otherwise fflush(fptr)- flush the buffer - usually for outputrewind(fptr)- setfptrto the beginning of file- The I/O functions above have more general versions for working with files, not just
stdin/stdout: put anfprefix on the name and addfileptrparameter:-
fprintf(fileptr, formatstring, ...); fscanf(fileptr, formatstring, ...);fgetc(fileptr); notefgetc(stdin) == getchar()fputc('c',fileptr); notefputc('c', stdout) == putchar('c')fputs(str,maxlength,fileptr); notemaxlengthis there to prevent buffer overrun holesfgets(str,maxlength,fileptr)
-
Binary Files
- Mostly declared/used the same way as text files
- Add a
"b"to the end of open mode passed tofopen
-- e.g.FILE fptr = fopen("items.dat","w+b");opens a binary file in"w+"mode. - Replace string read/write (e.g.
fscanf/fprintf) with binary data read/write (fread/fwrite) -
freadandfwritecan write raw binary data-
12as binary is hex0xC -
12as text is two characters, hex0x3132 - Note how binary
12takes 1/4th the bits to represent - Pictures, movies, music formats are generally binary to save space
-
-
fwritedirectly writes a C variable contents to a file:
fwrite (varptr, sizeof(vartype), n, fptr);varptrpoints to the data to write,vartypeis its type,nis how many,fptris a*FILE- Example
int i = 5; fwrite(&i,sizeof(int),1,fptr);writes0x00000005to the filefptrpoints to. - When
n > 1it writes an array:int a [] = {5,6,7}; fwrite(a,sizeof(int),3,fptr);writes0x000000050000000600000007 - (Well, it probably actually writes
0x050000000600000007000000because your computer is likely using little endian format.
- On Unix you can use the shell command
hexdump -C items.datto view the fileitems.datas binary data.) - Reading
fread(varaddr, sizeof(vartype), n, fptr);is the inverse of writing- Example
int i; fread(&i,sizeof(int),1,fptr);would read the value5(from above) intoiif the file was rewound to the beginning
- Example
Random access files
- Any
FILE* fptris always pointing to a spot in the file where it is going to next read/write - With random access you are explicitly moving this pointer around
fseek(fptr,nbytes, SEEK_SET);sets fptr to positionSEEK_SETmeans basis point we offset from is file start (absolute)SEEK_CURmeans point to offset from is the current location (relative)nbytesis the # of bytes to offset;(n-1)*sizeof(vartype)is the kind of expression usually put there (like in malloc)
fseekfrom the file start (withSEEK_SET) is very similar to how pointer arithmetic does array offsets. But, pointer arithmetic automatically factors in thesizeofinformation.-
ftell(fptr)return the current file pointer position (# bytes offset from 0 == beginning)