Programming in C: Standard File Pointers
Programming in C: Standard File Pointers
Programming in C
Input Output
Files
A collection of related data treated as a unit
Two types
Text
Binary
Stored in secondary storage devices
Buffer
Temporary storage area that holds data while they are
being transferred to or from memory.
111 Ch 16 1
V3 1/3/2015
Text Files
Data is mainly stored as human-readable characters
Each line of data ends with a newline character
= \n
C666666666 20 8.55
A222222222 50 12.5
F333333333 45 8.5
B444444444 50 9
G555555555 30 6
E111111111 40 10
H777777777 40 12
D888888888 40 11.11
I999999999 45 15
111 Ch 16 2
V3 1/3/2015
2. fopen
FILE * fopen(char * filename, char * mode)
Parameters
filename – string that supplies the name of the file as
known to the external world
Default path is current directory
mode Meaning
r Open file for reading
• If file exists, the marker is positioned at beginning
fopen
FILE * fopen(char * filename, char * mode)
Return
If successful, file pointer
If not successful, NULL
Always check return
If not successful, print error message and exit
or some other corrective action
fopen
FILE * fopen(char * filename, char * mode)
Examples
111 Ch 16 3
V3 1/3/2015
4. fclose
int fclose(FILE *fp)
Used to close a file when no longer needed
Prevents associated file from being accessed again
Guarantees that data stored in the stream buffer is
written to the file
Releases the FILE structure so that it can be used with
another file
Frees system resources, such as buffer space
Returns zero on success, or EOF on failure
10
fclose
Examples:
11
3. Input/Output Functions
Formatted Input
fscanf
Formatted Output
fprintf
String Input
fgets
String Output
fputs
12
111 Ch 16 4
V3 1/3/2015
Input
13
Output
14
Input
String Input
Reminder: Watch size of string
Must be large enough to hold largest input string
Plus \n perhaps
Plus \0 perhaps
C generally gives no warning of this issue
Standard Input
getchar: Read one character and return value as int
int getchar()
gets(): Read line & convert \n to \0, no size check
char *gets (char *strPtr)
15
111 Ch 16 5
V3 1/3/2015
Input
16
Output
String Output
Standard Output
putchar: Write one character
int putchar(int outChar)
puts(): Write line & converting \0 to \n
int puts (const char *strPtr)
17
Output
18
111 Ch 16 6
V3 1/3/2015
19
Programming in C
THE END
20
111 Ch 16 7