4. <stdio.h> Input and Output
The header <stdio.h> provides facilities for input and output.
A stream is a source or destination of data that may be associated with a disk or other peripheral. The library supports text streams and binary streams, although on some systems, notably UNIX or LINUX, these are identical.
A text stream is a sequence of lines; each line has zero or more characters and is terminated by '\n'. An environment may need to convert a text stream to or from some other representation because marks used for end of a line in text files may be different from '\n':
Windows | carriage return (CR, '\r') and linefeed (LF, '\n') |
Macintosh | carriage return (CR, '\r') |
UNIX, LINUX | linefeed (LF, '\n') |
A binary stream is a sequence of unprocessed bytes that record internal data, with the property that if it is written, then read back on the same system, it will compare equal.
A stream is connected to a file or device by opening it; the connection is broken by closing the stream. Opening a file returns a pointer to an object of type FILE, which records whatever information is necessary to control the stream. We will use file pointer and stream interchangeably when there is no ambiguity.
When a program begins execution, three standard streams are already open:
stdin | FILE *; standard input stream |
stdout | FILE *; standard output stream |
stderr | FILE *; standard error stream |
4.1 File Operations
The following functions deal with operations on files. The type size_t is the unsigned integral type produced by the sizeof operator.
FILE *fopen(const char *filename, const char *mode)
fopen opens the named file, and returns a stream, or NULL if the attempt fails. Legal values for mode include:
"r" | open text file for reading |
"w" | create text file for writing; discard previous contents if any |
"a" | append; open or create text file for writing at end of file |
"r+" | open text file for update (i.e., reading and writing) |
"w+" | create text file for update, discard previous contents if any |
"a+" | append; open or create text file for update, writing at end |
Update mode permits reading and writing the same file; fflush or a file-positioning function must be called between a read and a write or vice versa. If the mode includes b at the end, as in "rb" or "w+b", that indicates a binary file. Filenames are limited to FILENAME_MAX characters. At most FOPEN_MAX files may be open at once.
FILE *freopen(const char *filename, const char *mode, FILE *stream)
freopen opens the file with the specified mode and associates the stream with it. It returns stream, or NULL if an error occurs. freopen is normally used to change the files associated with stdin, stdout, or stderr.
int fclose(FILE *stream)
fclose flushes any unwritten data for stream, discards any unread buffered input, frees any automatically allocated buffer, then closes the stream. It returns EOF if any errors occurred, and zero otherwise.
int remove(const char *filename)
remove removes the named file; a subsequent attempt to open it will fail. It returns non-zero if the attempt fails.
int rename(const char *oldname, const char *newname)
rename changes the name of a file. It returns non-zero if the attempt fails.
FILE *tmpfile(void)
tmpfile creates a temporary file of mode "w+b" that will be automatically removed when closed or when the program terminates normally. tmpfile returns a stream, or NULL if it could not create the file.
char *tmpnam(char s[L_tmpnam])
tmpnam(NULL) creates a string that is not the name of an existing file, and returns a pointer to an internal static array. tmpnam(s) stores the string in s as well as returning it as the function value; s must have room for at least L_tmpnam characters. tmpnam generates a different name each time it is called; at most TMP_MAX different names are guaranteed during execution of the program. Note that tmpnam creates a name, not a file.
int fflush(FILE *stream)
On an output stream, fflush causes any buffered but unwritten data to be written; on an input stream, the effect is undefined. It returns EOF for a write error, and zero otherwise. fflush(NULL) flushes all output streams.
int setvbuf(FILE *stream, char *buf, int mode, size_t size)
setvbuf controls buffering for the stream. It must be called before reading, writing or any other operation. Legal values for mode include:
_IOFBF | full buffering |
_IOLBF | line buffering of text files |
_IONBF | no buffering |
If buf is not NULL, it will be used as the buffer, otherwise a buffer will be allocated. size determines the buffer size. setvbuf returns non-zero for any error.
void setbuf(FILE *stream, char *buf)
If buf is NULL, buffering is turned off for the stream. Otherwise, setbuf is equivalent to
(void)setvbuf(stream, buf, _IOFBF, BUFSIZ)
causing full buffering with the buffer size BUFSIZ.
4.2 Formatted Output
The printf functions provide formatted output conversion.
int fprintf(FILE *stream, const char *format, ...)
fprintf converts and writes output to stream under the control of format. The return value is the number of characters written, or negative if an error occurred.
The format string contains two types of objects: ordinary characters, which are copied to the output stream, and conversion specifications, each of which causes conversion and printing of the next successive argument to fprintf. Each conversion specification begins with the character % and ends with a conversion character. Between the % and the conversion character there may be, in order:
l Format flags (in any order), which modify the specification:
s -: specifies left adjustment of the converted argument in its field.
s +: specifies that the number will always be printed with a sign.
s space: if the first character is not a sign, a space will be prefixed.
s 0: for numeric conversions, specifies padding to the field width with leading zeros.
s #: specifies an alternate output form. For o, the first digit will become zero. For x or X, 0x or 0X will be prefixed to a non-zero result. For e, E, f, g, and G, the output will always have a decimal point; for g and G, trailing zeros will not be removed.
l A number specifying a minimum field width. The converted argument will be printed in a field at least this wide, and wider if necessary. If the converted argument has fewer characters than the field width it will be padded on the left (or right, if left adjustment has been requested) to make up the field width. The padding character is normally space, but is 0 if the zero padding flag is present.
l A period, which separates the field width from the precision.
l A number, the precision, that specifies the maximum number of characters to be printed from a string, or the number of digits to be printed after the decimal point for e, E, or f conversions, or the number of significant digits for g or G conversion, or the number of digits to be printed for an integer (leading 0s will be added to make up the necessary width).
l A qualifier h, l (letter ell), or L. h indicates that the corresponding argument is to be printed as a short or unsigned short; l indicates that the argument is a long or unsigned long, L indicates that the argument is a long double.
Field width and precision may be specified as *, in which case the value is computed by converting the next argument, which must be int.
The conversion characters and their meanings are shown in the following table.
d, i | int; signed decimal notation. |
O | int; unsigned octal notation (without a leading zero). |
x, X | int; unsigned hexadecimal notation (without a leading 0x or 0X), using abcdef for 0x or ABCDEF for 0X. |
u | int; unsigned decimal notation. |
c | int; single character, after conversion to unsigned char |
s | char *; characters from the string are printed until a '\0' is reached or until the number of characters indicated by the precision have been printed. |
f | double; decimal notation of the form [-]mmm.ddd, where the number of d's is given by the precision. The default precision is 6; a precision of 0 suppresses the decimal point. |
e, E | double; decimal notation of the form [-]m.ddde+/-xxx or [-]m.dddE+/-xxx, where the number of d's is specified by the precision. The default precision is 6; a precision of 0 suppresses the decimal point. |
g, G | double; %e or %E is used if the exponent is less than -4 or greater than or equal to the precision; otherwise %f is used. Trailing zeros and a trailing decimal point are not printed. The default precision (the number of significant digits) is 6. |
p | void *; print as a pointer (implementation-dependent representation). |
n | int *; the number of characters written so far by this call to printf is written into the argument. No argument is converted. |
% | No argument is converted; print a %. |
int printf(const char *format, ...)
printf(...) is equivalent to fprintf(stdout, ...).
int sprintf(char *s, const char *format, ...)
sprintf is the same as printf except that the output is written into the string s, terminated with '\0'. s must be big enough to hold the result. The return count does not include the '\0'.
int vprintf(const char *format, va_list arg)
int vfprintf(FILE *stream, const char *format, va_list arg)
int vsprintf(char *s, const char *format, va_list arg)
The functions vprintf, vfprintf, and vsprintf are equivalent to the corresponding printf functions, except that the variable argument list is replaced by arg initialized by the va_start macro (in <stdarg.h>).
4.3 Formatted Input
The scanf function deals with formatted input conversion.
int fscanf(FILE *stream, const char *format, ...)
fscanf reads from stream under control of format, and assigns converted values through subsequent arguments, each of which must be a pointer. It returns when format is exhausted. fscanf returns EOF if end of file or an error occurs before any conversion; otherwise it returns the number of input items converted and assigned.
The format string usually contains conversion specifications, which are used to direct interpretation of input. The format string may contain:
l Blanks or tabs, which are expected to match the longest possible sequence of zero or more white space characters (blank, tab, newline, carriage return, vertical tab, and formfeed) in the input.
l Ordinary characters (not %), which are expected to match the next non-white space character in the input.
l Conversion specifications, consisting of a %, an optional assignment suppression character *, an optional number specifying a maximum field width, an optional qualifier h, l, or L indicating the width of the target, and a conversion character or a scan set (represented as […]).
A conversion specification determines the conversion of the next input field. Normally the result is placed in the variable pointed to by the corresponding argument. If assignment suppression is indicated by *, as in %*s, however, the input field is simply skipped; no assignment is made. An input field is defined as a string of non-white space characters; it extends either to the next white space character or until the field width, if specified, is exhausted. This implies that scanf will read across line boundaries to find its input, since newlines are white space.
The conversion characters or scan sets shown in the following table indicate the interpretation of the input field. The corresponding argument must be a pointer. The conversion characters d, i, o, u, x, X and n may be preceded by h if the argument is a pointer to short rather than int, or by l (letter ell) if the argument is a pointer to long. The conversion characters e, E, g, G, and f may be preceded by l if a pointer to double rather than float is in the argument list, and by L if a pointer to long double.
d | int *; decimal integer. |
i | int *; integer. The integer may be in octal (leading 0) or hexadecimal (leading 0x or 0X). |
o | unsigned int *; unsigned octal integer (with or without leading zero). |
u | unsigned int *; unsigned decimal integer. |
x, X | unsigned int *; unsigned hexadecimal integer (with or without leading 0x or 0X). |
c | char *; characters. The next input characters are placed in the indicated array, up to the number given by the width field; the default is 1. No '\0' is added. The normal skip over white space characters is suppressed in this case; to read the next non-white space character, use %1s. |
s | char *; string of non-white space characters (not quoted), pointing to an array of characters large enough to hold the string; a terminating '\0' that will be added. |
f, e, E, g, G | float *; floating-point number. The input format for float’s is an optional sign, a string of numbers possibly containing a decimal point, and an optional exponent field containing an E or e followed by a possibly signed integer. |
p | void *; pointer value as printed by %p. |
n | int *; writes into the argument the number of characters read so far by this call. No input is read. The converted item count is not incremented. |
[...] | char *; matches the longest non-empty string of input characters from the set between brackets. A '\0' is added. []...] includes ] in the set. |
[^...] | char *; matches the longest non-empty string of input characters not from the set between brackets. A '\0' is added. [^]...] includes ] in the set. |
% | No assignment is made; literal %. |
int scanf(const char *format, ...)
scanf(...) is identical to fscanf(stdin, ...).
int sscanf(const char *s, const char *format, ...)
sscanf(s, ...) is equivalent to scanf(...) except that the input characters are taken from the string s.
4.4 Error Functions
Many of the functions in the library set status indicators when error or end of file occur. These indicators may be set and tested explicitly. In addition, the integer expression errno (in <errno.h>) may contain an error number that gives further information about the most recent error.
int feof(FILE *stream)
feof returns non-zero (true) if the end of file indicator for stream is set.
int ferror(FILE *stream)
ferror returns non-zero (true) if the error indicator for stream is set.
void clearerr(FILE *stream)
clearerr clears the end of file and error indicators for stream.
void perror(const char *s)
perror(s) prints s and an implementation-defined error message corresponding to errno, as if by
fprintf(stderr, "%s: %s\n", s, "error message")
4.5 Character and Line Input and Output
int fgetc(FILE *stream)
fgetc returns the next character of stream as an unsigned char (converted to an int), or EOF if end of file or error occurs.
int getc(FILE *stream)
getc is equivalent to fgetc except that if it is a macro, it may evaluate stream more than once.
int getchar(void)
getchar is equivalent to getc(stdin).
int fputc(int c, FILE *stream)
fputc writes the character c (converted to an unsigend char) on stream. It returns the character written, or EOF for error.
int putc(int c, FILE *stream)
putc is equivalent to fputc except that if it is a macro, it may evaluate stream more than once.
int putchar(int c)
putchar(c) is equivalent to putc(c, stdout).
char *gets(char *s)
gets reads, from stdin, the next input line into the array s; it replaces the terminating newline with '\0'. It returns s, or NULL if end of file or error occurs.
int puts(const char *s)
puts writes the string s and a newline to stdout. It returns EOF if an error occurs, non-negative otherwise.
char *fgets(char *s, int n, FILE *stream)
fgets reads at most the next n-1 characters into the array s, stopping if a newline is encountered; the newline is included in the array, which is terminated by '\0'. fgets returns s, or NULL if end of file or error occurs.
int fputs(const char *s, FILE *stream)
fputs writes the string s on stream. It returns non-negative, or EOF for an error.
int ungetc(int c, FILE *stream)
ungetc pushes c (converted to an unsigned char) back onto stream, where it will be returned on the next read. Only one character of pushback per stream is guaranteed. EOF may not be pushed back. ungetc returns the character pushed back, or EOF for error.
4.6 Direct Input and Output
size_t fread(void *ptr, size_t size, size_t nobj, FILE *stream)
fread reads from stream into the array ptr at most nobj objects of size size. It returns the number of objects read; this may be less than the number requested. feof and ferror must be used to determine status.
size_t fwrite(const void *ptr, size_t size, size_t nobj, FILE *stream)
fwrite writes, from the array ptr, nobj objects of size size on stream. It returns the number of objects written, which is less than nobj on error.
4.7 File Positioning
long ftell(FILE *stream)
ftell returns the current file position for stream, or -1 on error.
int fseek(FILE *stream, long offset, int origin)
fseek sets the file position for stream; a subsequent read or write will access data beginning at the new position. For a binary file, the position is set to offset characters from origin, which may be:
SEEK_SET | beginning |
SEEK_CUR | current position |
SEEK_END | end of file |
For a text stream, offset must be zero, or a value returned by ftell (in which case origin must be SEEK_SET). fseek returns non-zero on error.
void rewind(FILE *stream)
rewind(fp) is equivalent to fseek(fp, 0L, SEEK_SET); clearerr(fp).
int fgetpos(FILE *stream, fpos_t *ptr)
fgetpos records the current position in stream in *ptr, for subsequent use by fsetpos. The type fpos_t is suitable for recording such values. fgetpos returns non-zero on error.
int fsetpos(FILE *stream, const fpos_t *ptr)
fsetpos positions stream at the position recorded by fgetpos in *ptr. fsetpos returns non-zero on error.
EXAMPLE CODES
1. stdio.h
l fop-1.c
#include <stdio.h>
#define OUT(fc, x) printf("%s = %" #fc "\n", #x, x)
void main() {
int n = 10;
char msg[] = "Hello";
OUT(c, 'A' + 1);
OUT(d, n);
OUT(g, n / 4.0);
OUT(s, msg);
OUT(s, "Hi! " "Bye~\n");
OUT(d, FILENAME_MAX);
OUT(d, FOPEN_MAX);
OUT(d, L_tmpnam);
OUT(d, TMP_MAX);
OUT(d, BUFSIZ);
}
> fop-1
'A' + 1 = B
n = 10
n / 4.0 = 2.5
msg = Hello
"Hi! " "Bye~\n" = Hi! Bye~
FILENAME_MAX = 260
FOPEN_MAX = 20
L_tmpnam = 14
TMP_MAX = 32767
BUFSIZ = 512
l fop-2.c
// #define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h> // exit
#pragma warning (disable:4996)
// to disable warning 4996 for deprecation in VC
void main() {
const char *fn = "tmp.txt";
FILE *fp;
int c;
if (!(fp = fopen(fn, "w+")))
fprintf(stderr, "fail to open %s\n", fn), exit(1);
fprintf(fp, "0123456789\n");
rewind(fp);
while ((c = getc(fp)) != EOF) putchar(c);
fclose(fp);
}
0123456789
> dir tmp.txt
ü file size: 12
l fop-3.c
#define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> #include <stdlib.h> // exit void main() { const char *fn = "tmp.txt"; FILE *fp; int c; if (!(fp = fopen(fn, "wb"))) fprintf(stderr, "fail to open %s\n", fn), exit(1); fprintf(fp, "01234"); fclose(fp); if (!(fp = fopen(fn, "a+b"))) fprintf(stderr, "fail to open %s\n", fn), exit(1); printf("char. at 0 => %c\n", getc(fp)); fseek(fp, 0, SEEK_SET); // But... fprintf(fp, "56789\n"); fseek(fp, 0, SEEK_SET); while ((c = getc(fp)) != EOF) putchar(c); fclose(fp); }
> fop-3
char. at 0 => 0
0123456789
> dir tmp.txt
ü file size: 11
l fop-4.c
#define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> #include <stdlib.h> // exit void main() { char tmp_name[L_tmpnam]; FILE *fp; char line[1000]; printf("%s\n", tmpnam(NULL)); tmpnam(tmp_name); printf("%s\n", tmp_name); printf("Temporary file will be created...\n"); printf("Press <Enter> to continue. "); gets(line); if (!(fp = tmpfile())) fprintf(stderr, "fail to tmpfile\n"), exit(1); printf("Created temporary file using 'tmpfile'.\n"); printf("Press <Enter> to continue. "); gets(line); }
> fop-4
\s4a4.
\s4a4.1
Temporary file will be created...
Press <Enter> to continue.
Created temporary file using 'tmpfile'.
Press <Enter> to continue.
n See the root directory in Windows.
l fop-5.c
#define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> #include <stdlib.h> // exit int main() { char fn_old[FILENAME_MAX], fn_new[FILENAME_MAX], fn_rem[FILENAME_MAX]; printf("Old file name: "); scanf("%s", fn_old); printf("New file name: "); scanf("%s", fn_new); if (rename(fn_old, fn_new)) fprintf(stderr, "fail to rename %s\n", fn_old), exit(1); printf("Renamed: %s => %s.\n", fn_old, fn_new); printf("File name to remove: "); scanf("%s", fn_rem); if (remove(fn_rem)) fprintf(stderr, "fail to remove %s\n", fn_rem), exit(1); printf("Removed %s.\n", fn_rem); }
> echo Hi. > hi.txt
> echo SKHU CC > memo.txt && dir /w
> fop-5
Old file name: memo.txt
New file name: note.txt
Renamed: memo.txt => note.txt.
File name to remove: hi.txt
Removed hi.txt.
> dir /w
l fop-6.c
#include <stdio.h> void main() { printf("Lee.\n"); printf("Kim.\n"); fprintf(stderr, "-- END --\n"); }
> fop-6
Lee.
Kim.
-- END --
> fop-6 > out
-- END --
> type out
Lee.
Kim.
> fop-6 2> eout
Lee.
Kim.
> type eout
-- END --
> fop-6 > out 2> eout
> type out
Lee.
Kim.
> type eout
-- END --
> fop-6 | sort > res
-- END --
> type res
Kim.
Lee.
l fop-7.c
#define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> int main() { if (!freopen("std-out", "w", stdout)) return fprintf(stderr, "fail to reopen stdout\n"), 1; printf("message\n"); return 0; }
> fop-7
> type std-out
message
n Buffering mode in general
s keyboard input: line buffered by OS
s console output: flushed after each output library function is called
s disk file: fully buffered
l fop-8.c
#define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> #include <stdlib.h> // exit void main() { const char *fn = "tmp.txt"; FILE *fp; if (!(fp = fopen(fn, "w"))) fprintf(stderr, "fail to open %s\n", fn), exit(1); fprintf(fp, "message\n"); exit(0); // normal termination }
> fop-8
> type tmp.txt
message
l fop-9.c
#define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> #include <stdlib.h> // abort, exit void main() { const char *fn = "tmp.txt"; FILE *fp; if (!(fp = fopen(fn, "w"))) fprintf(stderr, "fail to open %s\n", fn), exit(1); fprintf(fp, "message\n"); abort(); // abnormal termination }
> fop-9
> type tmp.txt
l fop-10.c
#define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> #include <stdlib.h> // abort, exit void main() { const char *fn = "tmp.txt"; FILE *fp; if (!(fp = fopen(fn, "w"))) fprintf(stderr, "fail to open %s\n", fn), exit(1); fprintf(fp, "message\n"); fflush(fp); abort(); // abnormal termination }
> fop-10
> type tmp.txt
message
l fop-11.c
#define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> #include <stdlib.h> // abort, exit void main() { const char *fn = "tmp.txt"; FILE *fp; if (!(fp = fopen(fn, "w"))) fprintf(stderr, "fail to open %s\n", fn), exit(1); if (setvbuf(fp, NULL, _IONBF, 0)) fprintf(stderr, "fail to setvbuf for %s\n", fn), exit(1); fprintf(fp, "message\n"); abort(); // abnormal termination }
> fop-11
> type tmp.txt
message
1.2 Formatted Output
#include <stdio.h> void main() { int n; printf("[%d][%i][%u]\n", -1, -1, -1); // [-1][-1][4294967295] printf("[%5d][%-5d]\n", 12, 12); // [ 12][12 ] printf("[%05d][%05d]\n", -12, 12); // [-0012][00012] printf("[% d][% d]\n", -12, 12); // [-12][ 12] printf("[%X][%#X]\n", -1, -1); // [FFFFFFFF][0XFFFFFFFF] printf("[%+d][%+d][%+d]\n", -1, 0, 1); // [-1][+0][+1] printf("[%f][%e][%g]\n", 3.45, 3.45, 3.45); // [3.450000][3.450000e+000][3.45] printf("[%5.2f][%5.2e][%5.2g]\n", 3.45, 3.45, 3.45); // [ 3.45][3.45e+000][ 3.5] printf("[%.0f][%.0e][%.0g][%g]\n", 1.0, 1.0, 1.0, 1.0); // [1][1e+000][1][1] printf("[%#.0f][%#.0e][%#.0g][%#g]\n", 1.0, 1.0, 1.0, 1.0); // [1.][1.e+000][1.][1.00000] printf("[%08X][%u][%p]\n", &n, &n, &n); // [0012FF6C][1245036][0012FF6C] printf("[%hd][%ld]\n", 0x10000 + 12, 12L); // [12][12] printf("[%f][%Lf]\n", 3.45F, 3.45L); // [3.450000][3.450000] printf("[%-+#8.0Lf]\n", (long double)123); // [+123. ] }
l printf-2.c
#define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> #include <string.h> void main() { char s[100]; { int w = 4, p = 1; printf("[%*f][%.*f][%*.*f]\n", w, 3.4, p, 3.4, w, p, 3.4); // [3.400000][3.4][ 3.4] } { int n1, n2, n3, n4; #ifdef WIN32 _set_printf_count_output(1); // for %n in VC #endif printf("0123456789\n"); n4 = printf("1%3d%nAB%n\n%n", 34, &n1, &n2, &n3); // 0123456789 // 1 34AB printf("%d, %d, %d, %d\n", n1, n2, n3, n4); // 4, 6, 7, 7 printf("%d\n", sprintf(s, "")); // 0 } { // to make "s1:s2:s3" char *s1 = "AB", *s2 = "CD", *s3 = "EF"; strcpy(s, s1); strcat(s, ":"); strcat(s, s2); strcat(s, ":"); strcat(s, s3); puts(s); // AB:CD:EF sprintf(s, "%s:%s:%s", s1, s2, s3); puts(s); // AB:CD:EF } }
> cl -DWIN32 printf-2.c
1.3 Formatted Input
#define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> void main() { char c; short h; unsigned short hu; long l; int i, i1, i2, i3, n, m, r; float f, f1, f2, f3; double d; long double ld; sscanf("A", "%c", &c); i = c; printf("%c %d %c %d\n", c, c, i, i); // A 65 A 65 sscanf("50000 50000 50000", "%hu %hd %lu", &hu, &h, &l); printf("%u %d %lu\n", hu, h, l); // 50000 -15536 50000 sscanf("12 12 12", "%d %o %x", &i1, &i2, &i3); printf("%d %d %d\n", i1, i2, i3); // 12 10 18 sscanf("12 012 0x12", "%d %d %d", &i1, &i2, &i3); printf("%d %d %d\n", i1, i2, i3); // 12 12 0 sscanf("12 012 0x12", "%i %i %i", &i1, &i2, &i3); printf("%d %d %d\n", i1, i2, i3); // 12 10 18 sscanf("3.4 3.4 3.4", "%f %lf %Lf", &f, &d, &ld); printf("%f %f %Lf\n", f, d, ld); // 3.400000 3.400000 3.400000 sscanf("3.4 34e-2 123", "%E %G %f", &f1, &f2, &f3); printf("%f %f %f\n", f1, f2, f3); // 3.400000 0.340000 123.000000 r = sscanf("1234", "%3d%n", &i, &n); printf("%d, %d, %d\n", i, n, r); // 123, 3, 1 m = -999; r = sscanf("1234 67", "%*d %d%n%d", &i, &n, &m); printf("%d, %d, %d, %d\n", i, n, m, r); // 67, 7, -999, 1 }
l scanf-2.c
#define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> void main() { int i, n = 10, *p = &n, *q; char s[100], c1, c2; sprintf(s, "%p", p); sscanf(s, "%p", &q); printf("%d\n", *q); // 10 sscanf(" A", "%c %c", &c1, &c2); printf("[%c][%c]\n", c1, c2); // [ ][A] sscanf(" abcd", "%3s", s); printf("[%s]\n", s); // [abc] sscanf(" ABCD", "%2c", s); printf("[%s]\n", s); // [ Ac] sscanf("ABxy-120_AB", "%[ABC]", s); puts(s); // AB sscanf("ABxy-120_AB", "%[A-Za-z0-9-]", s); puts(s); // ABxy-120 sscanf("A[10].12", "%[][A-Za-z0-9]", s); puts(s); // A[10] sscanf("A[10].12", "%[^][]", s); puts(s); // A sscanf("AB-ab123", "%*[^0-9]%d", &i); // skip unless digits printf("%d\n", i); // 123 }
l scanf-3.c
// input month(mm) & date(dd) in mm:dd or mm/dd format #define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> #include <stdlib.h> void main() { char line[100]; int mm, dd, n; while (gets(line)) { if ((n = sscanf(line, "%d:%d", &mm, &dd)) != 2 && (n = sscanf(line, "%d/%d", &mm, &dd)) != 2) fprintf(stderr, "format: mm:dd or mm/dd\n"), exit(1); printf("%d월 %d일\n", mm, dd); } }
> scanf-3
10:9
10월 9일
10/9
10월 9일
10 9
format: mm:dd or mm/dd
l scanf_s.c
// scanf_s, fscanf_s, sscanf_s in VC -- not standard void main() { char c, s1[5], s2[5]; int n, r, r1, r2, r3; r = sscanf_s("A abc abc1234", "%c %s %[a-z] %d", &c, 1, s1, 5, s2, 5, &n); printf("%d, [%c][%s][%s][%d]\n", r, c, s1, s2, n); // 4, [A][abc][abc][1234] sscanf_s("1234567890", "%3s %4s", s1, 5, s2, 5); printf("[%s][%s]\n", s1, s2); // [123][4567] r1 = sscanf_s("abcde", "%2c", &c, 1); r2 = sscanf_s("abcde", "%5s", s1, 5); r3 = sscanf_s("abcde", "%s", s2, 5); printf("[%c:%d][%s][%s]\n", c, c, s1, s2); // [ :0][][] printf("%d, %d, %d\n", r1, r2, r3); // 0, 0, 0 // If no width specification field is used, // and the token read is too big to fit in the buffer, // nothing will be written to that buffer. }
l calc.c
// calculator: number op number, op = + - * / % #define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> #include <math.h> // fmod -- floating-point modulo operation void main() { char s[100], r; double x, y; char op; while (printf(">> "), gets(s)) { if (sscanf(s, "%lf %c %lf %c", &x, &op, &y, &r) != 3) continue; switch (op) { case '+': printf(" => %g\n", x + y); break; case '-': printf(" => %g\n", x - y); break; case '*': printf(" => %g\n", x * y); break; case '/': if (y != 0.0) printf(" => %g\n", x / y); break; case '%': if (y != 0.0) printf(" => %g\n", fmod(x, y)); break; } } }
> calc
>> 1.2 + 3.4
=> 4.6
>> 3.4-2
=> 1.4
>> 10* -2.5
=> -25
>> 10 / -4
=> -2.5
>> 10 % 4
=> 2
>> 0.1 % 0.03
=> 0.01
>> 0.1 % -0.03
=> 0.01
>> -0.1 % 0.03
=> -0.01
>> -0.1 % -0.03
=> -0.01
>> 10 / 0
>> 10 # 5
>> 1 + 2 + 3
>> ^Z
l sum.c
// sum of input data #define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> void main() { double d, sum = 0.0; while (fscanf(stdin, "%lf", &d) == 1) sum += d; if (!feof(stdin)) fprintf(stderr, "bad data\n"), exit(1); if (ferror(stdin)) fprintf(stderr, "input error\n"), exit(1); printf("sum = %g\n", sum); }
> sum
10 20
30 40
^Z
sum = 100
> sum
10 20 A
bad data
l fcopy-bug.c
// text file copy from stdin to stdout -- buggy version #define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> void main() { char c; while (!feof(stdin)) { scanf("%c", &c); printf("%c", c); } }
> type in
ABC
> dir in
ü file size: 3 -- no '\r\n' at end
> fcopy-bug < in
ABCC
l fcopy.c
// text file copy from stdin to stdout #include <stdio.h> void main() { int c; while ((c = getchar()) != EOF) putchar(c); }
> fcopy < in > out
> type out
ABC
> dir out
ü file size: 3 -- same as 'in'
1.5 Character and Line Input and Output
// display files with line numbers // usage: line-num [file ...] // if no file, then use stdin #define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> #include <string.h> // strlen #define LSIZE 10 // recommend larger size such as 1000 void display(FILE *fp); void main(int argc, char **argv) { FILE *fp; const char *fn; if (argc == 1) { printf("=== <stdin> ===\n"); display(stdin); return; } while ((fn = *++argv)) { if (!(fp = fopen(fn, "r"))) { fprintf(stderr, "ERROR: fail to open %s\n", fn); continue; } printf("=== %s ===\n", fn); display(fp); fclose(fp); } } void display(FILE *fp) { char line[LSIZE]; int no = 0, len; while (fgets(line, LSIZE, fp)) { printf("%4d: %s", ++no, line); while (line[strlen(line) - 1] != '\n') { // too long line if (!fgets(line, LSIZE, fp)) { putchar('\n'); return; } fputs(line, stdout); } } }
> line-num
=== <stdin> ===
동해물과 백두산이 마르고 닳도록
1: 동해물과 백두산이 마르고 닳도록
하느님이 보우하사 우리나라 만세
2: 하느님이 보우하사 우리나라 만세
^Z
> line-num < f1
=== <stdin> ===
1: [fgets]
2: fgets reads at most the next n-1 characters into the array s...
> line-num f1 f2
=== f1 ===
1: [fgets]
2: fgets reads at most the next n-1 characters into the array s...
=== f2 ===
1: [fputs]
2:
3: fputs writes the string s on stream.
4: It returns non-negative, or EOF for an error.
l token.c
// tokenize integers and operators -- +, -, *, /, %, (, ) #define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> #include <string.h> // strchr #include <ctype.h> // isspace, isdigit #define TOKEN_SIZE 1000 enum ETT { // token types TT_OPR, // operator TT_NUM, // number TT_BAD, // bad token TT_EOF // EOF }; const char *TK_NAMES[] = { "Operator", "Number" }; enum ETT get_token(char *token); void main() { char token[TOKEN_SIZE]; enum ETT tt; while ((tt = get_token(token)) <= TT_NUM) printf("%s: %s\n", TK_NAMES[tt], token); if (tt == TT_BAD) fprintf(stderr, "bad token: %s\n", gets(token)); } // get a token enum ETT get_token(char *token) { static const char *ops = "+-*/%()"; char *p = token; int c; while (isspace(c = getchar())) ; // skip white spaces if (strchr(ops, c)) // operator { token[0] = c; token[1] = '\0'; return TT_OPR; } if (c == EOF) return TT_EOF; // EOF if (!isdigit(c)) // bad token { ungetc(c, stdin); return TT_BAD; } // number *p++ = c; while (isdigit(c = getchar())) *p++ = c; *p = '\0'; if (c != EOF) ungetc(c, stdin); return TT_NUM; }
> token
123 * (45+67)
Number: 123
Operator: *
Operator: (
Number: 45
Operator: +
Number: 67
Operator: )
-12
Operator: -
Number: 12
^Z
> token
123 * abc - 456
Number: 123
Operator: *
bad token: abc - 456
1.6 Direct Input and Output
l fpos.c
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
void main() {
const char *fn = "tmp.txt";
FILE *fp; fpos_t ptr;
if (!(fp = fopen(fn, "w+b")))
fprintf(stderr, "%s: open error\n", fn), exit(1);
fprintf(fp, "01234");
if (fgetpos(fp, &ptr))
fclose(fp), fprintf(stderr, "%s: fgetpos error\n", fn), exit(1);
fprintf(fp, "56789\r\n");
if (fsetpos(fp, &ptr))
fclose(fp), fprintf(stderr, "%s: fsetpos error\n", fn), exit(1);
printf("char. at file position %d: ", ftell(fp));
printf("%c\n", getc(fp));
fclose(fp);
}
> fpos
char. at file position 5: 5
> type tmp.txt
0123456789
l fcopy.c
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#define USAGE "Usage: fcopy from to\n"
int main(int argc, char *argv[]) {
FILE *fpi, *fpo; char buf[BUFSIZ]; size_t n;
if (argc != 3)
return fprintf(stderr, "%s", USAGE), 1;
if (!(fpi = fopen(argv[1], "rb")))
return fprintf(stderr, "fail to open %s\n", argv[1]), 1;
if (!(fpo = fopen(argv[2], "wb")))
return fprintf(stderr, "fail to open %s\n", argv[2]), 1;
while ((n = fread(buf, 1, BUFSIZ, fpi)) > 0)
if (fwrite(buf, 1, n, fpo) != n) break;
if (ferror(fpi) || ferror(fpo))
return fprintf(stderr, "error during copy\n"), 1;
fclose(fpi); fclose(fpo); return 0;
}
> fcopy fcopy.exe fc.exe
> dir fcopy.exe fc.exe
ü check if file sizes are equal
> fc.exe xxx
Usage: fcopy from to
l fsize.c
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
#define USAGE "Usage: fsize files ...\n"
long file_size(const char *fn);
void main(int argc, char *argv[]) {
long fsize;
if (argc < 2) fprintf(stderr, "%s", USAGE), exit(1);
while (*++argv)
if ((fsize = file_size(*argv)) >= 0)
printf("%10ld %s\n", fsize, *argv);
}
// return file size(>= 0) or negative if error
long file_size(const char *fn) {
long fsize = -1L; const char *emsg; FILE *fp;
if (!(fp =fopen(fn, "r"))) emsg = "fopen";
else if (fseek(fp, 0, SEEK_END)) emsg = "fseek";
else if ((fsize = ftell(fp)) < 0) emsg = "ftell";
if (fp) fclose(fp);
if (fsize < 0) fprintf(stderr, "Error: %s -- %s\n", fn, emsg);
return fsize;
}
> fsize xxx fsize.obj fsize.exe
Error: xxx -- fopen
1424 fsize.obj
65536 fsize.exe
> dir xxx fsize.obj fsize.exe
n Tiny Project: Student Data Handling (1)
s stud.h, stud.c, make_sdat.c, show_sdat.c, find_sdat.c
l stud.h
#ifndef __STUD_H__
#define __STUD_H__
#define SNAME_SIZE 10 // student name size
typedef struct { // student record type
int id; // student ID
char name[SNAME_SIZE+1]; // student name
double gpa; // grade point average
} STUD_T;
// output a student record
void out_stud(FILE *fp, const STUD_T *ps);
#endif
l stud.c
#include <stdio.h>
#include "stud.h"
void out_stud(FILE *fp, const STUD_T *ps) {
fprintf(fp, "%8d => %-*s %.2f\n",
ps->id, SNAME_SIZE, ps->name, ps->gpa);
}
l make_sdat.c
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include "stud.h"
#define USAGE "Usage: make_sdat output_data_file\n"
#define NO_STUD (sizeof STUD_DATA / sizeof STUD_DATA[0])
STUD_T STUD_DATA[] = { // already sorted by 'id' field
{ 2000001, "강감찬", 2.81 },
{ 2000002, "곽재우", 3.62 },
{ 2000005, "을지문덕", 3.88 },
{ 2000006, "이순신", 2.99 },
{ 2000008, "이순신", 3.77 },
};
int main(int argc, char **argv) {
FILE *fp; const char *fn = argv[1];
if (argc != 2) return fprintf(stderr, "%s", USAGE), 1;
if (!(fp = fopen(fn, "wb")))
return fprintf(stderr, "error in opening %s\n", fn), 1;
if (fwrite(STUD_DATA, sizeof STUD_DATA[0], NO_STUD, fp) != NO_STUD)
return fprintf(stderr, "error in writing to %s\n", fn), 1;
fclose(fp); return 0;
}
l show_sdat.c
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include "stud.h"
#define USAGE "Usage: show_sdat input_data_file\n"
int main(int argc, char **argv) {
FILE *fp; const char *fn = argv[1]; STUD_T s;
if (argc != 2) return fprintf(stderr, "%s", USAGE), 1;
if (!(fp = fopen(fn, "rb")))
return fprintf(stderr, "error in opening %s\n", fn), 1;
while (fread(&s, sizeof s, 1, fp) == 1)
out_stud(stdout, &s);
if (ferror(fp))
return fprintf(stderr, "error in reading from %s\n", fn), 1;
fclose(fp); return 0;
}
l find_sdat.c
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include "stud.h"
#define USAGE "Usage: find_sdat input_data_file\n"
long find_stud(FILE *fp, int id, long no_stud, STUD_T *ps);
int main(int argc, char **argv) {
FILE *fp; const char *fn = argv[1]; STUD_T s;
int id; long fsize, no_stud, n;
if (argc != 2) return fprintf(stderr, "%s", USAGE), 1;
if (!(fp = fopen(fn, "rb")))
return fprintf(stderr, "error in opening %s\n", fn), 1;
if (fseek(fp, 0, SEEK_END))
return fprintf(stderr, "error in seeking %s\n", fn), 1;
if ((fsize = ftell(fp)) < 0 || fsize % sizeof s != 0)
return fprintf(stderr, "bad data in %s\n", fn), 1;
no_stud = fsize / sizeof s;
printf("# of student records = %ld\n", no_stud);
while (1) {
printf("student ID = ");
if (scanf("%d", &id) != 1) break;
if ((n = find_stud(fp, id, no_stud, &s)) >= 0)
printf("[%d] ", n), out_stud(stdout, &s);
else
printf("%d: not found\n", id);
}
fclose(fp); return 0;
}
// Find a student record of the ID 'id' from the file 'fp'.
// If found, set '*ps' and return the record number(>= 0).
// Otherwise, return negative.
// high(no_stud): # of student records
// Algorithm: binary search for file records
// Student records must be sorted by 'id' field.
long find_stud(FILE *fp, int id, long high /* no_stud */, STUD_T *ps) {
long low = 0, mid;
while (low < high) {
mid = (low + high) / 2;
if (fseek(fp, mid * sizeof *ps, SEEK_SET) ||
fread(ps, sizeof *ps, 1, fp) != 1) return -1;
if (id < ps->id) high = mid;
else if (id > ps->id) low = mid + 1;
else return mid;
}
return -1;
}
> cl make_sdat.c stud.c
> cl -c stud.c
> cl make_sdat.c stud.obj
> cl show_sdat.c stud.obj
> cl find_sdat.c stud.obj
> make_sdat s.dat
> dir s.dat
ü check if file size == (# of records) * (record size)
ü 120 == 5 * 24
> show_sdat s.dat
2000001 => 강감찬 2.81
2000002 => 곽재우 3.62
2000005 => 을지문덕 3.88
2000006 => 이순신 2.99
2000008 => 이순신 3.77
> find_sdat s.dat
# of student records = 5
student ID = 2000005
[2] 2000005 => 을지문덕 3.88
student ID = 2000008
[4] 2000008 => 이순신 3.77
student ID = 2000010
2000010: not found
student ID = ^Z
No comments:
Post a Comment