=========
STDIO.H
=========
Functions
=========
clearerr
fclose
fcloseall
fdopen
feof
ferror
fflush
fgetc
fgetchar
fgetpos
fgets
fileno
flushall
fopen
fprintf
fputc
fputchar
fputs
fread
freopen
fscanf
fseek
fsetpos
ftell
fwrite
getc
getchar
gets
getw
perror
printf
putc
putchar
puts
putw
remove
rename
rewind
rmtmp
scanf
setbuf
setvbuf
sprintf
sscanf
strerror
_strerror
tempnam
tmpfile
tmpnam
ungetc
unlink
vfprintf
vfscanf
vprintf
vscanf
vsprintf
vsscanf
Constants, data types, and global variables
===========================================
buffering modes
BUFSIZ
EOF
_F_BIN
_F_BUF
_F_EOF
_F_ERR
_F_IN
_F_LBUF
_F_OUT
_F_RDWR
_F_READ
_F_TERM
_F_WRIT
FILE
FOPEN_MAX
fpos_t
fseek/lseek modes
_IOFBF
_IOLBF
_IONBF
L_ctermid
L_tmpnam
NULL
SEEK_CUR
SEEK_END
SEEK_SET
size_t
stdaux
stderr
stdin
stdout
stdprn
SYS_OPEN
TMP_MAX
See Also
========
List of all Header files
stdaux, stderr, stdin,
stdout, and stdprn <STDIO.H>
========================
Predefined streams automatically opened
when the program is started.
Name | Meaning
--------+-----------------------------------
stdin | Standard input device
stdout | Standard output device
stderr | Standard error output device
stdaux | Standard auxiliary device
stdprn | Standard printer
_F_xxxx <STDIO.H>
=========
File status flags of streams
Name | Meaning
---------+--------------------------
_F_RDWR | Read and write
_F_READ | Read-only file
_F_WRIT | Write-only file
_F_BUF | Malloc'ed buffer data
_F_LBUF | Line-buffered file
_F_ERR | Error indicator
_F_EOF | EOF indicator
_F_BIN | Binary file indicator
_F_IN | Data is incoming
_F_OUT | Data is outgoing
_F_TERM | File is a terminal
_IOxxx <STDIO.H>
========
Constants for defining buffering style to be
used with a file.
Name | Meaning
--------+-----------------------------------------------------------------
_IOFBF | The file is fully buffered.
| When a buffer is empty, the next input operation will attempt
| to fill the entire buffer.
| On output, the buffer will be completely filled before any
| data is written to the file.
_IOLBF | The file is line buffered.
| When a buffer is empty, the next input operation will still
| attempt to fill the entire buffer.
| On output, however, the buffer will be flushed whenever
| a newline character is written to the file.
_IONBF | The file is unbuffered.
| The buf and size parameters are ignored. Each input operation
| will read directly from the file, and each output operation
| will immediately write the data to the file.
See Also:
setvbuf
BUFSIZ <STDIO.H>
========
Default buffer size used by setbuf function.
EOF <STDIO.H>
=====
A constant indicating that end-of-file has
been reached on a file.
L_ctermid <STDIO.H>
===========
The length of a device id string.
L_tmpnam <STDIO.H>
==========
Size of an array large enough to hold a
temporary file name string.
TMP_MAX <STDIO.H>
=========
Maximum number of unique file names.
OPEN #defines <STDIO.H>
===============
Number of files that can be open
simultaneously.
Name | Meaning
-----------+----------------------------
FOPEN_MAX | Maximum files per process
SYS_OPEN | Maximum files for system
fpos_t <STDIO.H>
========
A file position type.
FILE <STDIO.H>
======
File control structure for streams.
typedef struct {
short level;
unsigned flags;
char fd;
unsigned char hold;
short bsize;
unsigned char *buffer, *curp;
unsigned istemp;
short token;
} FILE;
_streams <STDIO.H>
==========
Array of type FILE used by the stream I/O
functions.
Declaration: extern FILE _streams[];
See Also:
List of all global variables
==========
clearerr <STDIO.H>
==========
Resets error indication
Declaration: void clearerr(FILE *stream);
Remarks:
clearerr resets the named stream's error and
end-of-file indicators to 0.
Once the error indicator is set, stream
operations continue to return error status
until a call is made to clearerr or rewind.
The end-of-file indicator is reset with each
input operation.
Return Value: None
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | Yes | |
+-----+------+---------+--------+----------+
See Also:
eof
feof
ferror
perror
Example:
#include <stdio.h>
int main(void)
{
FILE *fp;
char ch;
/* open a file for writing */
fp = fopen("DUMMY.FIL", "w");
/* force an error condition by attempting to read */
ch = fgetc(fp);
printf("%c\n",ch);
if (ferror(fp))
{
/* display an error message */
printf("Error reading from DUMMY.FIL\n");
/* reset the error and EOF indicators */
clearerr(fp);
}
fclose(fp);
return 0;
}
========
fclose <STDIO.H>
========
Closes a stream
Declaration: int fclose(FILE *stream);
Remarks:
fclose closes the named stream.
All buffers associated with the stream are
flushed before closing.
System-allocated buffers are freed upon
closing.
Buffers assigned with setbuf or setvbuf are
not automatically freed. (But if setvbuf is
passed null for the buffer pointer, it will
free it upon close.)
Return Value
* On success, returns 0
* On error, returns EOF
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | Yes | |
+-----+------+---------+--------+----------+
See Also:
close
fcloseall
fdopen
fflush
flushall
fopen
freopen
Example:
#include <string.h>
#include <stdio.h>
int main(void)
{
FILE *fp;
char buf[11] = "0123456789";
/* create a file containing 10 bytes */
fp = fopen("DUMMY.FIL", "w");
fwrite(&buf, strlen(buf), 1, fp);
/* close the file */
fclose(fp);
return 0;
}
===========
fcloseall <STDIO.H>
===========
Closes all open streams
Declaration: int fcloseall(void);
Remarks:
fcloseall closes all open streams except
stdin, stdout, stdprn, stderr, and stdaux.
Return Value:
* On success, returns the total number of streams it closed
* On error, returns EOF
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | | |
+-----+------+---------+--------+----------+
See Also:
fclose
fdopen
flushall
fopen
freopen
Example:
#include <stdio.h>
int main(void)
{
int streams_closed;
/* open two streams */
fopen("DUMMY.ONE", "w");
fopen("DUMMY.TWO", "w");
/* close the open streams */
streams_closed = fcloseall();
if (streams_closed == EOF)
/* issue an error message */
perror("Error");
else
/* print result of fcloseall() function */
printf("%d streams were closed.\n", streams_closed);
return 0;
}
======
feof <STDIO.H>
======
Macro that tests if end-of-file has been reached on a stream.
Declaration: int feof(FILE *stream);
Remarks:
feof is a macro that tests the given stream
for an end-of-file indicator.
Once the indicator is set, read operations on
the file return the indicator until rewind is
called, or the file is closed.
The end-of-file indicator is reset with each
input operation.
Return Value:
* Returns non-zero if an end-of-file
indicator was detected on the last input
operation on the named stream.
* Returns 0 if end-of-file has not been
reached.
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | Yes | |
+-----+------+---------+--------+----------+
See Also:
clearerr
eof
Example:
#include <stdio.h>
int main(void)
{
FILE *stream;
/* open a file for reading */
stream = fopen("DUMMY.FIL", "r");
/* read a character from the file */
fgetc(stream);
/* check for EOF */
if (feof(stream))
printf("We have reached end-of-file\n");
/* close the file */
fclose(stream);
return 0;
}
========
ferror <STDIO.H>
========
Macro that tests if an error has occurred on a stream
Declaration: int ferror(FILE *stream);
Remarks:
ferror is a macro that tests the given stream
for a read or write error.
If the stream's error indicator has been set,
it remains set until clearerr or rewind is
called, or until the stream is closed.
Return Value:
ferror returns non-zero if an error was
detected on the named stream.
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | Yes | |
+-----+------+---------+--------+----------+
See Also:
clearerr
eof
fopen
rewind
Example:
#include <stdio.h>
int main(void)
{
FILE *stream;
/* open a file for writing */
stream = fopen("DUMMY.FIL", "w");
/* force an error condition by attempting to read */
(void) getc(stream);
if (ferror(stream)) /* test for an error on the stream */
{
/* display an error message */
printf("Error reading from DUMMY.FIL\n");
/* reset the error and EOF indicators */
clearerr(stream);
}
fclose(stream);
return 0;
}
========
fflush <STDIO.H>
========
Flushes a stream
Declaration: int fflush(FILE *stream);
Remarks:
If the given stream has buffered output,
fflush writes the output for stream to the
associated file.
The stream remains open after fflush has
executed. fflush has no effect on an
unbuffered stream.
Return Value
* On success, returns 0
* On error, returns EOF
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | Yes | |
+-----+------+---------+--------+----------+
See Also:
fclose
flushall
setbuf
setvbuf
Example:
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <io.h>
void flush(FILE *stream);
int main(void)
{
FILE *stream;
char msg[] = "This is a test";
/* create a file */
stream = fopen("DUMMY.FIL", "w");
/* write some data to the file */
fwrite(msg, strlen(msg), 1, stream);
clrscr();
printf("Press any key to flush DUMMY.FIL:");
getch();
/* flush the data to DUMMY.FIL without closing it */
flush(stream);
printf("\nFile was flushed, Press any key to quit:");
getch();
return 0;
}
void flush(FILE *stream)
{
int duphandle;
/* flush the stream's internal buffer */
fflush(stream);
/* make a duplicate file handle */
duphandle = dup(fileno(stream));
/* close the duplicate handle to flush the DOS buffer */
close(duphandle);
}
==============
fgetc, fputc <STDIO.H>
==============
* fgetc gets a character from a stream
* fputc outputs a character to a stream
Declaration:
* int fgetc(FILE *stream);
* int fputc(int c, FILE *stream);
Remarks:
fgetc returns the next character on the named
input stream. It is a function version of the
getc macro.
fputc outputs character c to the named stream.
Return Value:
* On success,
* fgetc returns the character read, after converting it to an int
without sign extension.
* fputc returns the character c.
* On end-of-file or error, fgetc returns EOF
* On error, fputc returns EOF
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | Yes | |
+-----+------+---------+--------+----------+
See Also:
fgetchar
getc
getch
getchar
getche
putc
ungetc
ungetch
Examples:
fgetc example
fputc example
fgetc example
===============
#include <string.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
FILE *stream;
char string[] = "This is a test";
char ch;
/* open a file for update */
stream = fopen("DUMMY.FIL", "w+");
/* write a string into the file */
fwrite(string, strlen(string), 1, stream);
/* seek to the beginning of the file */
fseek(stream, 0, SEEK_SET);
do
{
/* read a char from the file */
ch = fgetc(stream);
/* display the character */
putch(ch);
} while (ch != EOF);
fclose(stream);
return 0;
}
fputc example
===============
#include <stdio.h>
int main(void)
{
char msg[] = "Hello world";
int i = 0;
while (msg[i])
{
fputc(msg[i], stdout);
i++;
}
return 0;
}
====================
fgetchar, fputchar <STDIO.H>
====================
* fgetchar gets a character from stdin
* fputchar outputs a character to stdout
Declaration:
* int fgetchar(void);
* int fputchar(int c);
Remarks:
fgetchar, which is defined as fgetc(stdin),
returns the next character from stdin.
fputchar(c), which is the same as
fputc(c, stdout), outputs character c to
stdout. fputchar is the function version of
the putchar macro.
Return Value:
* On success,
* fgetchar returns the character read,
after converting it to an int without
sign extension.
* fputchar returns the character c.
* On end-of-file or error, fgetchar returns EOF
* On error, fputchar returns EOF
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | | |
+-----+------+---------+--------+----------+
See Also:
getchar
fgetc
Examples:
fgetchar example
fputchar example
fgetchar example
==================
#include <stdio.h>
int main(void)
{
char ch;
/* prompt the user for input */
printf("Enter a character followed by <Enter>: ");
/* read the character from stdin */
ch = fgetchar();
/* display what was read */
printf("The character read is: '%c'\n", ch);
return 0;
}
fputchar example
==================
#include <stdio.h>
int main(void)
{
char msg[] = "This is a test";
int i = 0;
while (msg[i])
{
fputchar(msg[i]);
i++;
}
return 0;
}
==================
fgetpos, fsetpos <STDIO.H>
==================
* fgetpos gets the current file pointer position
* fsetpos positions the file pointer of a stream
Declaration:
* int fgetpos(FILE *stream, fpos_t *pos);
* int fsetpos(FILE *stream, const fpos_t *pos);
Remarks:
fgetpos stores the position of the file
pointer associated with the given stream in
the location *pos.
The value stored contains unspecified
information that can be used by fsetpos to
reposition the stream to the position it was
in at the time of the call to fgetpos.
fsetpos sets the file pointer associated with
stream to a new position. The new position is
the value obtained by a previous call to
fgetpos on that stream.
fsetpos also clears the end-of-file indicator
on the file *stream and undoes any effects of
ungetc on that file.
After a call to fsetpos, the next operation
on the file can be input or output.
Return Value
* On success, both functions return 0
* On error,
* fgetpos returns a non-zero value and sets errno to EBADF or EINVAL
* fsetpos returns a non-zero value and sets errno to a non-zero value
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | | Yes | Yes | |
+-----+------+---------+--------+----------+
See Also:
fseek
ftell
tell
Example (for both functions):
#include <stdlib.h>
#include <stdio.h>
void showpos(FILE *stream);
int main(void)
{
FILE *stream;
fpos_t filepos;
/* open a file for update */
stream = fopen("DUMMY.FIL", "w+");
/* save the file pointer position */
fgetpos(stream, &filepos);
/* write some data to the file */
fprintf(stream, "This is a test");
/* show the current file position */
showpos(stream);
/* set a new file position, display it */
if (fsetpos(stream, &filepos) == 0)
showpos(stream);
else
{
fprintf(stderr, "Error setting file pointer.\n");
exit(1);
}
/* close the file */
fclose(stream);
return 0;
}
void showpos(FILE *stream)
{
fpos_t pos;
/* display the current file pointer
position of a stream */
fgetpos(stream, &pos);
printf("File position: %ld\n", pos);
}
==============
fgets, fputs <STDIO.H>
==============
* fgets gets a string from a stream
* fputs outputs a string to a stream
Declaration:
* char *fgets(char *s, int n, FILE *stream);
* int fputs(const char *s, FILE *stream);
Remarks:
fgets reads characters from stream into the
string s. It stops when it reads either n - 1
characters or a newline character, whichever
comes first.
fgets retains the newline character at the
end of s and appends a null byte to s to mark
the end of the string.
fputs copies the null-terminated string s to
the given output stream. It does not append
a newline character, and the terminating null
character is not copied.
Return Value:
* On success,
* fgets returns the string pointed to by s.
* fputs returns the last character written.
* On end-of-file or error, fgets returns null.
* On error, fputs returns EOF.
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | Yes | |
+-----+------+---------+--------+----------+
See Also:
cgets
gets
puts
Examples:
fgets example
fputs example
fgets example
===============
#include <string.h>
#include <stdio.h>
int main(void)
{
FILE *stream;
char string[] = "This is a test";
char msg[20];
/* open a file for update */
stream = fopen("DUMMY.FIL", "w+");
/* write a string into the file */
fwrite(string, strlen(string), 1, stream);
/* seek to the start of the file */
fseek(stream, 0, SEEK_SET);
/* read a string from the file */
fgets(msg, strlen(string)+1, stream);
/* display the string */
printf("%s", msg);
fclose(stream);
return 0;
}
fputs example
===============
#include <stdio.h>
int main(void)
{
/* write a string to standard output */
fputs("Hello world\n", stdout);
return 0;
}
========
fileno <STDIO.H>
========
Macro that returns the file handle associated with a stream
Declaration: int fileno(FILE *stream);
Remarks:
fileno is a macro that returns the file
handle for the stream.
If stream has more than one handle, fileno
returns the handle assigned to the stream
when it was first opened.
Return Value:
fileno returns the integer file handle
associated with stream.
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | | |
+-----+------+---------+--------+----------+
Example:
#include <stdio.h>
int main(void)
{
FILE *stream;
int handle;
/* create a file */
stream = fopen("DUMMY.FIL", "w");
/* obtain the file handle associated with the stream */
handle = fileno(stream);
/* display the handle number */
printf("handle number: %d\n", handle);
/* close the file */
fclose(stream);
return 0;
}
==========
flushall <STDIO.H>
==========
Flushes all open streams
Declaration: int flushall(void);
Remarks:
flushall clears all buffers associated with
open input streams, and writes all buffers
associated with open output streams to their
respective files.
Any read operation following flushall reads
new data into the buffers from the input
files.
Streams stay open after flushall executes.
Return Value:
Returns an integer, the number of open input
and output streams.
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | | |
+-----+------+---------+--------+----------+
See Also:
fclose
fcloseall
fflush
Example:
#include <stdio.h>
int main(void)
{
FILE *stream;
/* create a file */
stream = fopen("DUMMY.FIL", "w");
/* flush all open streams */
printf("%d streams were flushed.\n", flushall());
/* close the file */
fclose(stream);
return 0;
}
=================================
fdopen, fopen, freopen, _fsopen <STDIO.H>
=================================
* fdopen associates a stream with a file handle
* fopen opens a stream
* freopen associates a new file with an open stream
* _fsopen opens a stream with file sharing
Declaration:
* FILE *fdopen(int handle, char *type);
* FILE *fopen(const char *filename, const char *mode);
* FILE *freopen(const char *filename, const char *mode, FILE *stream);
* _fsopen:
#include <stdio.h>
#include <share.h>
FILE *_fsopen(const char *filename, const char *mode, int shflg);
Remarks:
* fdopen associates a stream with a file
handle obtained from creat, dup, dup2, or
open.
* fopen and _fsopen open a file and associate
a stream with it. Both functions return a
pointer that identifies the stream in
subsequent operations.
* freopen substitutes a file in place of the
open stream and closes the stream, regardless
of whether the open succeeds. freopen is
useful for changing the file attached to
stdin, stdout, or stderr.
Argument| Function | What Argument Is/Does
---------+----------------+------------------------------------------------
handle | fdopen | File handle from creat, dup, dup2, or open
type | fdopen | Type of the stream; must match the mode of
| | the open handle.
---------+----------------+------------------------------------------------
filename| fopen, _fsopen | File that the functions open
| freopen | File substituted in place of the open stream
---------+----------------+------------------------------------------------
mode | fopen, freopen,| Mode string: defines the mode of the opened
| and _fsopen | file (r, w, a, r+, w+, a+, etc.)
---------+----------------+------------------------------------------------
stream | freopen | Open stream, substituted by filename
shflag | _fsopen | Specifies the type of file sharing allowed on
| | filename.
Symbolic constants for shflag are defined in
SHARE.H. The file-sharing flags are ignored
if the DOS SHARE command has not been run.
When a file is opened for update, both input
and output can be done on the resulting
stream. However:
* output can't be directly followed by input
without an intervening fseek or rewind
* input can't be directly followed by output
without an intervening fseek or rewind, or
an input that encounters end-of-file
Return Value:
* On success,
* fdopen, fopen, and _fsopen return a
pointer to the newly opened stream
* freopen returns the argument stream
* On error, these functions return null
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
fdopen | Yes | Yes | Yes | | |
fopen | Yes | Yes | Yes | Yes | |
freopen | Yes | Yes | Yes | Yes | |
_fsopen | Yes | | Yes | | |
+-----+------+---------+--------+----------+
See Also:
creat
_dos_open
dup/dup2
fclose
ferror
FILE
_fmode
fread
fseek
fwrite
open
rewind
setbuf
setmode
sopen
Examples:
fdopen example
fopen example
freopen example
_fsopen example
_fsopen example
=================
#include <io.h>
#include <process.h>
#include <share.h>
#include <stdio.h>
int main(void)
{
FILE *f;
int status;
f = _fsopen("c:\\autoexec.bat", "r", SH_DENYNO);
if (f == NULL)
{
printf("_fsopen failed\n");
exit(1);
}
status = access("c:\\autoexec.bat", 6);
if (status == 0)
printf("read/write access allowed\n");
else
printf("read/write access not allowed\n");
fclose(f);
return 0;
}
fdopen example
================
#include <sys\stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
int main(void)
{
int handle;
FILE *stream;
/* open a file */
handle = open("DUMMY.FIL", O_CREAT,
S_IREAD | S_IWRITE);
/* now turn the handle into a stream */
stream = fdopen(handle, "w");
if (stream == NULL)
printf("fdopen failed\n");
else
{
fprintf(stream, "Hello world\n");
fclose(stream);
}
return 0;
}
fopen example
===============
/* Program to create backup of the AUTOEXEC.BAT file */
#include <stdio.h>
int main(void)
{
FILE *in, *out;
if ((in = fopen("\\AUTOEXEC.BAT", "rt"))
== NULL)
{
fprintf(stderr, "Cannot open input file.\n");
return 1;
}
if ((out = fopen("\\AUTOEXEC.BAK", "wt"))
== NULL)
{
fprintf(stderr, "Cannot open output file.\n");
return 1;
}
while (!feof(in))
fputc(fgetc(in), out);
fclose(in);
fclose(out);
return 0;
}
freopen example
=================
#include <stdio.h>
int main(void)
{
/* redirect standard output to a file */
if (freopen("OUTPUT.FIL", "w", stdout)
== NULL)
fprintf(stderr, "error redirecting stdout\n");
/* this output will go to a file */
printf("This will go into a file.");
/* close the standard output stream */
fclose(stdout);
return 0;
}
==============================
mode string and type string
==============================
The mode string used in calls to fopen,
freopen, and _fsopen (or the type string used
in calls to fdopen) is one of the following
values:
String| Description
-------+------------------------------------------------------------------
r | Open for reading only
w | Create for writing
| If a file by that name already exists, it will be overwritten.
a | Append; open for writing at end of file, or create for
| writing if the file does not exist.
r+ | Open an existing file for update (reading and writing)
w+ | Create a new file for update (reading and writing).
| If a file by that name already exists, it will be overwritten.
a+ | Open for append; open for update at the end of the file, or
| create if the file does not exist.
* To specify that a given file is being opened or created in text mode,
append "t" to the string (rt, w+t, etc.).
* To specify binary mode, append "b" to the string (wb, a+b, etc.).
fopen and _fsopen also allow the "t" or "b"
to be inserted between the letter and the +
character in the string. For example, rt+ is
equivalent to r+t.
If "t" or "b" is not given in the string, the
mode is governed by _fmode.
* If _fmode is set to O_BINARY, files are opened in binary mode.
* If _fmode is set to O_TEXT, they are opened in text mode.
These O_... constants are defined in FCNTL.H.
=======
fread <STDIO.H>
=======
Reads data from a stream
Declaration:
size_t fread(void *ptr, size_t size, size_t n, FILE *stream);
Remarks:
fread reads a specified number of equal-sized
data items from an input stream into a block.
Argument| What It Is/Does
--------+-------------------------------------------
ptr | Points to a block into which data is read
size | Length of each item read, in bytes
n | Number of items read
stream | Points to input stream
The total number of bytes read is (n * size).
Return Value:
* On success, fread returns the number of items (not bytes) actually read
* On end-of-file or error, fread returns a short count (possibly 0)
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | Yes | |
+-----+------+---------+--------+----------+
See Also:
fopen
fwrite
printf
read
Example:
#include <string.h>
#include <stdio.h>
int main(void)
{
FILE *stream;
char msg[] = "this is a test";
char buf[20];
if ((stream = fopen("DUMMY.FIL", "w+"))
== NULL)
{
fprintf(stderr, "Cannot open output file.\n");
return 1;
}
/* write some data to the file */
fwrite(msg, strlen(msg)+1, 1, stream);
/* seek to the beginning of the file */
fseek(stream, SEEK_SET, 0);
/* read the data and display it */
fread(buf, strlen(msg)+1, 1, stream);
printf("%s\n", buf);
fclose(stream);
return 0;
}
=======
fseek <STDIO.H>
=======
Repositions the file pointer of a stream
Declaration: int fseek(FILE *stream, long offset, int whence);
Remarks:
fseek sets the file pointer associated with a
stream to a new position.
Argument| What It Is/Does
--------+----------------------------------------------------------------
stream | Stream whose file pointer fseek sets
offset | Difference in bytes between whence (a file pointer position)
| and new position. For text mode streams, offset should be 0 or
| a value returned by ftell.
whence | One of three SEEK_xxx file pointer locations (0, 1, or 2)
fseek discards any character pushed back
using ungetc.
fseek is used with stream I/O. For file
handle I/O, use lseek.
After fseek, the next operation on an update
file can be either input or output.
fseek can return a 0 (indicating that the
pointer has been moved successfully), when it
has not been. This is because DOS, which
actually resets the pointer, does not verify
the setting.
Return Value:
* On success (the pointer is successfully moved), fseek returns 0.
* On failure, fseek returns a non-zero value. fseek returns an error code
only on an unopened file or device.
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | Yes | |
+-----+------+---------+--------+----------+
See Also:
fgetpos
fopen
fsetpos
ftell
lseek
rewind
setbuf
tell
Example:
#include <stdio.h>
long filesize(FILE *stream);
int main(void)
{
FILE *stream;
stream = fopen("MYFILE.TXT", "w+");
fprintf(stream, "This is a test");
printf("Filesize of MYFILE.TXT is %ld bytes\n", filesize(stream));
fclose(stream);
return 0;
}
long filesize(FILE *stream)
{
long curpos, length;
curpos = ftell(stream);
fseek(stream, 0L, SEEK_END);
length = ftell(stream);
fseek(stream, curpos, SEEK_SET);
return length;
}
=======
ftell <STDIO.H>
=======
Returns the current file pointer
Declaration: long ftell(FILE *stream);
Remarks:
ftell returns the current file pointer for
stream.
If the file is binary, the offset is measured
in bytes from the beginning of the file
The value returned by ftell can be used in a
subsequent call to fseek.
Return Value:
* On success, returns the current file
pointer position.
* On error, returns -1L and sets errno to a
positive value.
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | Yes | |
+-----+------+---------+--------+----------+
See Also:
fgetpos
fseek
fsetpos
lseek
rewind
tell
Example:
#include <stdio.h>
int main(void)
{
FILE *stream;
stream = fopen("MYFILE.TXT", "w+");
fprintf(stream, "This is a test");
printf("The file pointer is at byte %ld\n", ftell(stream));
fclose(stream);
return 0;
}
========
fwrite <STDIO.H>
========
Writes to a stream
Declaration:
size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);
Remarks:
fwrite appends a specified number of
equal-sized data items to an output file.
Argument| What It Is/Does
--------+-------------------------------------------------------
ptr | Pointer to any object; the data written begins at ptr
size | Length of each item of data
n | Number of data items to be appended
stream | Specifies output file
The total number of bytes written is
(n * size)
Return Value:
* On success, returns the number of items (not bytes) actually written.
* On error, returns a short count.
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | Yes | |
+-----+------+---------+--------+----------+
See Also:
fopen
fread
Example:
#include <stdio.h>
struct mystruct
{
int i;
char ch;
};
int main(void)
{
FILE *stream;
struct mystruct s;
if ((stream = fopen("TEST.$$$", "wb")) == NULL) /* open file TEST.$$$ */
{
fprintf(stderr, "Cannot open output file.\n");
return 1;
}
s.i = 0;
s.ch = 'A';
fwrite(&s, sizeof(s), 1, stream); /* write struct s to file */
fclose(stream); /* close file */
return 0;
}
===============
getc and putc <STDIO.H>
===============
* getc is a macro that gets one character from a stream
* putc is a macro that outputs a character to a stream
Declaration:
* int getc(FILE *stream);
* int putc(int c, FILE *stream);
Remarks:
getc returns the next character on the given
input stream and increments the stream's file
pointer to point to the next character.
putc outputs the character given by c to the
stream given by stream.
Return Value:
* On success,
* getc returns the character read, after converting it to an int
without sign extension.
* putc returns the character given by c.
* On error (and on end-of-file for getc), both functions return EOF.
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | Yes | |
+-----+------+---------+--------+----------+
See Also:
fgetc
fprintf
fputc
fputchar
fputs
fwrite
getch
getchar
getche
gets
printf
putch
putchar
putw
ungetc
vfprintf
Examples:
getc example
putc example
getc example
==============
#include <stdio.h>
int main(void)
{
char ch;
printf("Input a character:");
/* read a character from the
standard input stream */
ch = getc(stdin);
printf("The character input was: '%c'\n", ch);
return 0;
}
putc example
==============
#include <stdio.h>
int main(void)
{
char msg[] = "Hello world\n";
int i = 0;
while (msg[i])
putc(msg[i++], stdout);
return 0;
}
==================
getchar, putchar <STDIO.H>
==================
* getchar is a macro that gets a character from stdin
* putchar is a macro that outputs a character on stdout
Declaration:
* int getchar(void);
* int putchar(int c);
Remarks:
getchar is a macro defined as getc(stdin)
getchar returns the next character on the
input stream stdin.
putchar is a macro defined as putc(c, stdout)
putchar puts the character given by c on the
output stream stdout.
Return Value:
* On success,
* getchar returns the character read, after converting it to an int
without sign extension.
* putchar returns the character given by c.
* On error (and on end-of-file for getchar), both macros return EOF.
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
getchar | Yes | Yes | | Yes | |
putchar | Yes | Yes | Yes | Yes | |
+-----+------+---------+--------+----------+
See Also:
fgetc
fgetchar
fputchar
getc
getch
getche
gets
printf
putc
putch
puts
putw
scanf
ungetc
vprintf
vscanf
Examples:
getchar example
putchar example
getchar example
=================
#include <stdio.h>
int main(void)
{
int c;
/* Note that getchar reads from stdin and
is line buffered; this means it will
not return until you press ENTER. */
while ((c = getchar()) != '\n')
printf("%c", c);
return 0;
}
putchar example
=================
#include <stdio.h>
/* define some box-drawing characters */
#define LEFT_TOP 0xDA
#define RIGHT_TOP 0xBF
#define HORIZ 0xC4
#define VERT 0xB3
#define LEFT_BOT 0xC0
#define RIGHT_BOT 0xD9
int main(void)
{
char i, j;
/* draw the top of the box */
putchar(LEFT_TOP);
for (i=0; i<10; i++)
putchar(HORIZ);
putchar(RIGHT_TOP);
putchar('\n');
/* draw the middle */
for (i=0; i<4; i++)
{
putchar(VERT);
for (j=0; j<10; j++)
putchar(' ');
putchar(VERT);
putchar('\n');
}
/* draw the bottom */
putchar(LEFT_BOT);
for (i=0; i<10; i++)
putchar(HORIZ);
putchar(RIGHT_BOT);
putchar('\n');
return 0;
}
============
gets, puts <STDIO.H>
============
* gets gets a string from stdin
* puts outputs a string to stdout (and appends a newline character)
Declaration:
* char *gets(char *s);
* int puts(const char *s);
Remarks:
* gets collects a string of characters
terminated by a new line from the standard
input stream stdin and puts it into s.
* puts copies the null-terminated string s to
the standard output stream stdout and appends
a newline character.
gets replaces the newline by a null character
(\0) in s; it also allows input strings to
contain certain whitespace characters
(spaces, tabs).
gets returns when it encounters a newline;
everything up to the newline is copied into
s.
Return Value:
* On success,
* gets returns the string argument s.
* puts returns a non-negative value.
* On end-of-file or error, gets returns null.
* On error, puts returns a value of EOF.
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | | Yes | |
+-----+------+---------+--------+----------+
See Also:
cgets
cputs
ferror
fgets
fopen
fputs
fread
getc
printf
putchar
scanf
Examples:
gets example
puts example
puts example
==============
#include <stdio.h>
int main(void)
{
char string[] = "This is an example output string\n";
puts(string);
return 0;
gets example
==============
#include <stdio.h>
int main(void)
{
char string[80];
printf("Input a string:");
gets(string);
printf("The string input was: %s\n", string);
return 0;
}
============
getw, putw <STDIO.H>
============
* getw gets an integer from stream
* putw outputs an integer on a stream
Declaration:
* int getw(FILE *stream);
* int putw(int w, FILE *stream);
Remarks:
* getw returns the next integer in the named
input stream. It assumes no special alignment
in the file. getw should not be used when the
stream is opened in text mode.
* putw outputs the integer w to the given
stream. It does not expect (and does not
cause) special alignment in the file.
Return Value:
* On success,
* getw returns the next integer on the input stream.
* putw returns the integer w.
* On error,
* getw returns EOF
* putw returns EOF
* On end-of-file, getw returns EOF
Because EOF is a legitimate value for getw to
return, use feof to detect end-of-file or
ferror to detect error.
Because EOF is a legitimate integer, use
ferror to detect errors with putw.
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | | |
+-----+------+---------+--------+----------+
See Also:
printf
Examples:
getw example
putw example
getw example
==============
#include <stdio.h>
#include <stdlib.h>
#define FNAME "test.$$$"
int main(void)
{
FILE *fp;
int word;
/* place the word in a file */
fp = fopen(FNAME, "wb");
if (fp == NULL)
{
printf("Error opening file %s\n", FNAME);
exit(1);
}
word = 94;
putw(word,fp);
if (ferror(fp))
printf("Error writing to file\n");
else
printf("Successful write\n");
fclose(fp);
/* reopen the file */
fp = fopen(FNAME, "rb");
if (fp == NULL)
{
printf("Error opening file %s\n", FNAME);
exit(1);
}
/* extract the word */
word = getw(fp);
if (ferror(fp))
printf("Error reading file\n");
else
printf("Successful read: word = %d\n", word);
/* clean up */
fclose(fp);
unlink(FNAME);
return 0;
}
putw example
==============
#include <stdio.h>
#include <stdlib.h>
#define FNAME "test.$$$"
int main(void)
{
FILE *fp;
int word;
/* place the word in a file */
fp = fopen(FNAME, "wb");
if (fp == NULL)
{
printf("Error opening file %s\n", FNAME);
exit(1);
}
word = 94;
putw(word,fp);
if (ferror(fp))
printf("Error writing to file\n");
else
printf("Successful write\n");
fclose(fp);
/* reopen the file */
fp = fopen(FNAME, "rb");
if (fp == NULL)
{
printf("Error opening file %s\n", FNAME);
exit(1);
}
/* extract the word */
word = getw(fp);
if (ferror(fp))
printf("Error reading file\n");
else
printf("Successful read: word = %d\n", word);
/* clean up */
fclose(fp);
unlink(FNAME);
return 0;
}
========
perror <STDIO.H>
========
Prints a System error message
Declaration: void perror(const char *s);
Remarks:
perror prints to the stderr stream (normally
the console) the system error message for the
last library routine that produced the error.
It prints the argument s, a colon, the
message corresponding to the current value of
errno, then a newline.
The convention is to pass the file name of
the program as the argument s.
Use sys_errlist to access the array of error
message strings.
You can use errno as an index into the array
to find the string corresponding to the error
number. None of the strings includes a
newline character.
sys_nerr contains the number of entries in
the array.
Return Value: None
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | | Yes | |
+-----+------+---------+--------+----------+
See Also:
clearerr
eof
_strerror
strerror
Example:
#include <stdio.h>
int main(void)
{
FILE *fp;
fp = fopen("perror.dat", "r");
if (!fp)
perror("Unable to open file for reading");
return 0;
}
=====================
...printf functions <CONIO.H, STDIO.H>
=====================
* cprintf sends formatted output to the text window on the screen
* fprintf sends formatted output to a stream
* printf sends formatted output to stdin
* sprintf sends formatted output to a string
* vfprintf sends formatted output to a stream, using an argument list
* vprintf sends formatted output to stdin, using an argument list
* vsprintf sends formatted output to a string, using an argument list
Declaration:
* int cprintf ( const char *format [, argument, ...]);
* int fprintf (FILE *stream, const char *format [, argument, ...]);
* int printf ( const char *format [, argument, ...]);
* int sprintf (char *buffer, const char *format [, argument, ...]);
* int vfprintf(FILE *stream, const char *format, va_list arglist);
* int vprintf ( const char *format, va_list arglist);
* int vsprintf(char *buffer, const char *format, va_list arglist);
Remarks:
All these functions are declared in STDIO.H,
except cprintf, which is declared in CONIO.H.
The ...printf functions do the following:
* Accept a series of arguments
* Apply to each argument a format specifier
contained in the format string *format
* Output the formatted data (to the screen,
a stream, stdin, or a string)
These functions apply the first format
specifier to the first argument, the second
specifier to the second argument, the third
to the third, etc., to the end of the format.
+----------------------------------------+
| NOTE |
|----------------------------------------|
| There must be enough arguments for the |
| format. |
| |
| If there are not, the results will be |
| unpredictable and likely disastrous. |
| |
| Excess arguments (more than required |
| by the format) are merely ignored. |
+----------------------------------------+
Argument| Functions | What Argument Is/Does
---------+-----------+----------------------
arglist | v...printf| Pointer to a list of
| | arguments
argument| cprintf, | One of a series of
| fprintf, | arguments to which
| printf, | the functions apply
| sprintf | a format specifier
| | contained in *format
buffer | sprintf, | Buffer where function
| vsprintf | writes the string
format | (all) | Format string
stream | fprintf, | Stream where the
| vfprintf | functions output the
| | formatted data
cprintf
=======
With cprintf, the string is written either
directly to screen memory or by way of a BIOS
call, depending on the value of directvideo.
cprintf does not translate linefeed
characters (\n) into carriage-return/linefeed
character pairs (\r\n).
The v...printf functions
========================
The v...printf functions are known as
alternate entry points for the ...printf
functions.
They behave exactly like their ...printf
counterparts, except they accept a pointer to
a list of arguments (va_list arglist) instead
of accepting an actual list of arguments
([, address, ...]).
* NOTE: When you use the SS!=DS flag, vprintf
assumes that the address being passed is in
the SS segment.
Return Value:
* On success, the ...printf functions return the number of bytes output
* cprintf returns the number of characters output
* sprintf does not include the terminating null byte in the count
* On error, these functions return EOF
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
cprintf | Yes | | | | |
fprintf | Yes | Yes | Yes | Yes | |
printf | Yes | Yes | | Yes | |
sprintf | Yes | Yes | Yes | Yes | |
vfprintf | Yes | Yes | Yes | Yes | |
vprintf | Yes | Yes | | Yes | |
vsprintf | Yes | Yes | | Yes | |
+-----+------+---------+--------+----------+
See Also:
atof
fscanf
getc
getche
putc
putch
va_arg
va_end
va_start
More ...printf topics
=====================
Format String
Format Specifiers
Format Specifier Conventions
Flag Characters
Input-size Modifiers
Precision Specifiers
Type Characters
Width Specifiers
Examples:
cprintf example
fprintf example
printf example
sprintf example
vfprintf example
vprintf example
vsprintf example
cprintf example
================
#include <conio.h>
int main(void)
{
/* clear the screen */
clrscr();
/* create a text window */
window(10, 10, 80, 25);
/* output some text in the window */
cprintf("Hello world\r\n");
/* wait for a key */
getch();
return 0;
}
fprintf example
================
#include <stdio.h>
int main(void)
{
FILE *stream;
int i = 100;
char c = 'C';
float f = 1.234;
/* open a file for update */
stream = fopen("DUMMY.FIL", "w+");
/* write some data to the file */
fprintf(stream, "%d %c %f", i, c, f);
/* close the file */
fclose(stream);
return 0;
}
printf example
===============
#include <stdio.h>
#include <string.h>
#define I 555
#define R 5.5
int main(void)
{
int i,j,k,l;
char buf[7];
char *prefix = buf;
char tp[20];
printf("prefix 6d 6o 8x 10.2e "
"10.2f\n");
strcpy(prefix,"%");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
for (k = 0; k < 2; k++)
for (l = 0; l < 2; l++)
{
if (i==0) strcat(prefix,"-");
if (j==0) strcat(prefix,"+");
if (k==0) strcat(prefix,"#");
if (l==0) strcat(prefix,"0");
printf("%5s |",prefix);
strcpy(tp,prefix);
strcat(tp,"6d |");
printf(tp,I);
strcpy(tp,"");
strcpy(tp,prefix);
strcat(tp,"6o |");
printf(tp,I);
strcpy(tp,"");
strcpy(tp,prefix);
strcat(tp,"8x |");
printf(tp,I);
strcpy(tp,"");
strcpy(tp,prefix);
strcat(tp,"10.2e |");
printf(tp,R);
strcpy(tp,prefix);
strcat(tp,"10.2f |");
printf(tp,R);
printf(" \n");
strcpy(prefix,"%");
}
}
return 0;
}
sprintf example
================
#include <stdio.h>
#include <math.h>
int main(void)
{
char buffer[80];
sprintf(buffer, "An approximation of Pi is %f\n", M_PI);
puts(buffer);
return 0;
}
vfprintf example
=================
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
FILE *fp;
int vfpf(char *fmt, ...)
{
va_list argptr;
int cnt;
va_start(argptr, fmt);
cnt = vfprintf(fp, fmt, argptr);
va_end(argptr);
return(cnt);
}
int main(void)
{
int inumber = 30;
float fnumber = 90.0;
char string[4] = "abc";
fp = tmpfile();
if (fp == NULL)
{
perror("tmpfile() call");
exit(1);
}
vfpf("%d %f %s", inumber, fnumber, string);
rewind(fp);
fscanf(fp,"%d %f %s", &inumber, &fnumber, string);
printf("%d %f %s\n", inumber, fnumber, string);
fclose(fp);
return 0;
}
vprintf example
================
#include <stdio.h>
#include <stdarg.h>
int vpf(char *fmt, ...)
{
va_list argptr;
int cnt;
va_start(argptr, fmt);
cnt = vprintf(fmt, argptr);
va_end(argptr);
return(cnt);
}
int main(void)
{
int inumber = 30;
float fnumber = 90.0;
char *string = "abc";
vpf("%d %f %s\n",inumber,fnumber,string);
return 0;
}
vsprintf example
=================
#include <stdio.h>
#include <conio.h>
#include <stdarg.h>
char buffer[80];
int vspf(char *fmt, ...)
{
va_list argptr;
int cnt;
va_start(argptr, fmt);
cnt = vsprintf(buffer, fmt, argptr);
va_end(argptr);
return(cnt);
}
int main(void)
{
int inumber = 30;
float fnumber = 90.0;
char string[4] = "abc";
vspf("%d %f %s", inumber, fnumber, string);
printf("%s\n", buffer);
return 0;
}
The ...printf Format String
============================
The format string controls how each ...printf
function converts, formats, and prints its
arguments.
The format string is a character string that
contains two types of objects:
* plain characters
* conversion specifications
Plain characters are simply copied verbatim
to the output stream.
Conversion specifications fetch arguments
from the argument list and apply formatting
to them.
See Also:
Format Specifiers
Format Specifier Conventions
Flag Characters
Input-size Modifiers
Precision Specifiers
Type Characters
Width Specifiers
...printf Format Specifiers
============================
In ...printf format strings, format specifiers
have the following form:
% [flags] [width] [.prec] [F|N|h|l|L] type_char
Each format specifier begins with the percent
character (%).
After the % come the following, in this order:
Component | What It Controls or Specifies
------------+-------------------------------------------
[flags] |(Optional) Flag character(s)
| Output justification, numeric signs, decimal
| points, trailing zeros, octal and hex prefixes
[width] |(Optional) Width specifier
| Minimum number of characters to print, padding
| with blanks or zeros
[.prec] |(Optional) Precision specifier
| Maximum number of characters to print; for
| integers, minimum number of digits to print
[F|N|h|l|L]|(Optional) Input size modifier
| Override default size of next input argument
| N = near pointer h = short int
| F = far pointer l = long int
| L = long double
type_char |(Required) Conversion type character
See Also:
Format String
Format Specifier Conventions
Flag Characters
Input-size Modifiers
Precision Specifiers
Type Characters
Width Specifiers
...printf Flag Characters
===========================
The ...printf flag characters specify output
justification, numeric signs, decimal points,
trailing zeros, and octal and hex prefixes.
The flag characters can appear in any order
and combination.
Flag | What It Means
------+--------------------------------------------------------------
- | Left-justifies the result, pads on the right with blanks.
| If not given, right-justifies result, pads on left with zeros
| or blanks.
|
+ | Signed conversion results always begin with a plus (+) or
| minus (-) sign.
|
blank| If value is non-negative, the output begins with a blank
| instead of a plus; negative values still begin with a minus.
|
# | Specifies that arg is to be converted using an "alternate form"
Plus (+) takes precedence over blank ( ) if
both are given.
See Also:
Format String
Format Specifiers
Format Specifier Conventions
Precision Specifiers
Type Characters
Width Specifiers
Alternate Forms for ...printf Conversion
==========================================
If you use the # flag with a ...printf
conversion character, it has the following
effect on the argument (arg) being converted:
Conversion|
character | How # affects the argument
-----------+----------------------------------------------------------
c s d i u | Has no effect
|
0 | Prepends 0 to a non-zero argument
|
x or X | Prepends 0x (or 0X) to argument
|
e E f | The result always contains a decimal point even if no
| digits follow the point. Normally, a decimal point
| appears in these results only if a digit follows it.
|
g G | Same as e and E; trailing zeros are not removed
See Also:
Format String
Format Specifiers
Format Specifier Conventions
Flag Characters
Input-size Modifiers
Precision Specifiers
Type Characters
Width Specifiers
...printf Width Specifiers
===========================
The ...printf width specifier sets the
minimum width for an output value.
Width is specified in one of two ways:
* directly, through a decimal digit string
* indirectly, through an asterisk (*)
If you use an "*" for the width specifier,
the next argument in the call (which must be
an int) specifies the minimum output field
width.
Nonexistent or small field widths do NOT
cause truncation of a field. If the result of
a conversion is wider than the field width,
the field is expanded to contain the
conversion result.
[width] | How Output Width Is Affected
---------+--------------------------------------------------------
n | At least n characters are printed.
| If the output value has less than n characters, the
| output is padded with blanks (right-padded if "-" flag
| is given, left-padded otherwise).
0n | At least n characters are printed.
| If the output value has less than n characters, it is
| filled on the left with zeros.
* | The argument list supplies the width specifier, which
| must precede the actual argument being formatted.
See Also:
Format String
Format Specifiers
Format Specifier Conventions
Flag Characters
Input-size Modifiers
Precision Specifiers
Type Characters
...printf Precision Specifiers
================================
The ...printf precision specifiers set the
maximum number of characters (or minimum
number of integer digits) to print.
A printf precision specification always
begins with a period (.) to separate it
from any preceding width specifier.
Then, like [width], precision is specified
in one of two ways:
* directly, through a decimal digit string
* indirectly, through an asterisk (*)
If you use an "*" for the precision
specifier, the next argument in the call
(treated as an int) specifies the precision.
If you use asterisks for the width or the
precision, or for both, the width argument
must immediately follow the specifiers,
followed by the precision argument, then the
argument for the data to be converted.
[.prec] | How Output Precision Is Affected
---------+-------------------------------------------------------
(none) | Precision set to default:
| = 1 for d, i, o, u, x, X types
| = 6 for e, E, f types
| = All significant digits for g, G types
| = Print to first null character for s types
| = No effect on c types
.0 | For d, i, o, u, x types, precision set to default;
| for e, E, f types, no decimal point is printed.
.n | n characters or n decimal places are printed.
| If the output value has more than n characters, the
| output might be truncated or rounded. (Whether this
| happens depends on the type character.)
* | The argument list supplies the precision specifier,
| which must precede the actual argument being formatted.
No numeric characters will be output for a
field (i.e., the field will be blank) if the
following conditions are all met:
* you specify an explicit precision of 0
* the format specifier for the field is one
of the integer formats (d, i, o, u, or x)
* the value to be printed is 0
How [.prec] affects conversion
==============================
Type|
Char| Effect of [.prec] (.n) on Conversion
----+----------------------------------------
d | Specifies that at least n digits are
i | printed.
o | * If input argument has less than n
u | digits, output value is left-padded
x | with zeros.
X | * If input argument has more than n
| digits, the output value is not
| truncated.
|
e | Specifies that n characters are
E | printed after the decimal point, and
f | the last digit printed is rounded.
|
g | Specifies that at most n significant
G | digits are printed.
|
c | Has no effect on the output.
|
s | Specifies that no more than n
| characters are printed.
See Also:
Format String
Format Specifiers
Format Specifier Conventions
Flag Characters
Input-size Modifiers
Type Characters
Width Specifiers
...printf Conversion-Type Characters
======================================
The information in this table is based on the
assumption that no flag characters, width
specifiers, precision specifiers, or
input-size modifiers were included in the
format specifier.
* NOTE: Certain conventions accompany some of
these format specifiers.
Type | |
Char | Expected Input | Format of output
------+----------------+---------------------------------------------------
Numerics
------+----------------+---------------------------------------------------
d | Integer | Signed decimal integer
i | Integer | Signed decimal integer
o | Integer | Unsigned octal integer
u | Integer | Unsigned decimal integer
x | Integer | Unsigned hexadecimal int (with a, b, c, d, e, f)
X | Integer | Unsigned hexadecimal int (with A, B, C, D, E, F)
f | Floating point | Signed value of the form [-]dddd.dddd.
e | Floating point | Signed value of the form [-]d.dddd or e[+/-]ddd
g | Floating point | Signed value in either e or f form, based on
| | given value and precision. Trailing zeros and
| | the decimal point are printed if necessary.
E | Floating point | Same as e; with E for exponent.
G | Floating point | Same as g; with E for exponent if e format used
------+----------------+---------------------------------------------------
Characters
------+----------------+---------------------------------------------------
c | Character | Single character
s | String pointer | Prints characters until a null-terminator is
| | pressed or precision is reached
% | None | Prints the % character
------+----------------+---------------------------------------------------
Pointers
------+----------------+---------------------------------------------------
n | Pointer to int | Stores (in the location pointed to by the input
| | argument) a count of the chars written so far.
p | Pointer | Prints the input argument as a pointer; format
| | depends on which memory model was used. It will
| | be either XXXX:YYYY or YYYY (offset only).
Infinite floating-point numbers are printed
as +INF and -INF.
An IEEE Not-A-Number is printed as +NAN or
-NAN.
See Also:
Format String
Format Specifiers
Format Specifier Conventions
Flag Characters
Input-size Modifiers
Precision Specifiers
Width Specifiers
...printf Input-size Modifiers
================================
These modifiers determine how ...printf
functions interpret the next input argument,
arg[f].
Modifier| Type of arg | arg is interpreted as ...
--------+-------------+-----------------------------------------------
F | Pointer (p, | A far pointer
N | s, and n) | A near pointer (NOTE: N can't be used with any
| | conversion in huge model.)
h | d i o u x X | A short int
l | d i o u x X | A long int
| e E f g G | A double
L | e E f g G | A long double
These modifiers affect how all the ...printf
functions interpret the data type of the
corresponding input argument arg.
Both F and N reinterpret the input variable
arg. Normally, the arg for a %p, %s, or %n
conversion is a pointer of the default size
for the memory model.
h, l, and L override the default size of the
numeric data input arguments. Neither h nor
l affects character (c, s) or pointer (p, n)
types.
See Also:
Format String
Format Specifiers
Format Specifier Conventions
Flag Characters
Precision Specifiers
Type Characters
Width Specifiers
...printf Format Specifier Conventions
=======================================
Certain conventions accompany some of the
...printf format specifiers.
This Help screen covers conventions for the
following conversions:
* %e or %E
* %f
* %g or %G
* %x or %X
See Also:
Format String
Format Specifiers
Flag Characters
Input-size Modifiers
Precision Specifiers
Type Characters
Width Specifiers
%e or %E Conversions
======================
The argument is converted to match the style
[-] d.ddd...e[+/-]ddd
where:
* one digit precedes the decimal point
* the number of digits after the decimal
point is equal to the precision.
* the exponent always contains at least
two digits
%f Conversions
================
The argument is converted to decimal notation
in the style
[-] ddd.ddd...
where the number of digits after the decimal
point is equal to the precision (if a
non-zero precision was given).
%g or %G Conversions
======================
The argument is printed in style e, E or f,
with the precision specifying the number of
significant digits.
Trailing zeros are removed from the result,
and a decimal point appears only if
necessary.
The argument is printed in style e or f (with
some restraints) if g is the conversion
character. Style e is used only if the
exponent that results from the conversion is
either greater than the precision or less
than -4.
The argument is printed in style E if G is
the conversion character.
%x or %X Conversions
======================
For x conversions, the letters a, b, c, d, e,
and f appear in the output.
For X conversions, the letters A, B, C, D, E,
and F appear in the output.
========
remove <STDIO.H>
========
Macro that removes a file
Declaration: int remove(const char *filename);
Remarks:
remove deletes the file specified by
filename.
It is a macro that simply translates its call
to a call to unlink.
If your file is open, be sure to close it
before removing it.
The string *filename can include a full DOS
path.
Return Value
* On success, remove returns 0.
* On error, it returns -1, and sets errno
to one of the following:
ENOENT No such file of directory
EACCES Permission denied
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | Yes | |
+-----+------+---------+--------+----------+
See Also:
unlink
Example:
#include <stdio.h>
int main(void)
{
char file[80];
/* prompt for file name to delete */
printf("File to delete: ");
gets(file);
/* delete the file */
if (remove(file) == 0)
printf("Removed %s.\n",file);
else
perror("remove");
return 0;
}
========
rename <STDIO.H>
========
Renames a file
Declaration: int rename(const char *oldname, const char *newname);
Remarks:
rename changes the name of a file from
oldname to newname.
If a drive specifier is given in newname, the
specifier must be the same as that given in
oldname.
Directories in oldname and newname do not
need to be the same, so rename can be used
to move a file from one directory to another.
Wildcards are not allowed.
Return Value:
* On success, returns 0.
* On error, returns -1 and sets errno to
one of the following:
ENOENT No such file or directory
EACCES Permission denied
ENOTSAM Not same device
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | | Yes | Yes | |
+-----+------+---------+--------+----------+
Example:
#include <stdio.h>
int main(void)
{
char oldname[80], newname[80];
/* prompt for file to rename and new name */
printf("File to rename: ");
gets(oldname);
printf("New name: ");
gets(newname);
/* Rename the file */
if (rename(oldname, newname) == 0)
printf("Renamed %s to %s.\n", oldname, newname);
else
perror("rename");
return 0;
}
========
rewind <STDIO.H>
========
Repositions file pointer to stream's beginning
Declaration: void rewind(FILE *stream);
Remarks:
rewind(stream) is equivalent to
fseek(stream, 0L, SEEK_SET)
except that rewind clears the end-of-file and
error indicators, while fseek only clears the
end-of-file indicator.
After rewind, the next operation on an update
file can be either input or output.
Return Value: None
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | Yes | |
+-----+------+---------+--------+----------+
See Also:
fopen
fseek
ftell
Example:
#include <stdio.h>
#include <dir.h>
int main(void)
{
FILE *fp;
char *fname = "TXXXXXX", *newname, first;
newname = mktemp(fname);
fp = fopen(newname,"w+");
fprintf(fp,"abcdefghijklmnopqrstuvwxyz");
rewind(fp);
fscanf(fp,"%c",&first);
printf("The first character is: %c\n",first);
fclose(fp);
remove(newname);
return 0;
}
=======
rmtmp <STDIO.H>
=======
Removes temporary files.
Declaration: int rmtmp(void);
Remarks:
rmtmp closes and deletes all open temporary
file streams, which were previously created
with tmpfile.
The current directory must the same as when
the files were created, or the files will not
be deleted.
Return Value:
Returns the total number of temporary files
closed and deleted.
Portability
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | | Yes | | |
+-----+------+---------+--------+----------+
See Also:
tmpfile
Example:
#include <stdio.h>
#include <process.h>
void main()
{
FILE *stream;
int i;
/* Create temporary files */
for (i = 1; i <= 10; i++)
{
if ((stream = tmpfile()) == NULL)
perror("Could not open temporary file\n");
else
printf("Temporary file %d created\n", i);
}
/* Remove temporary files */
if (stream != NULL)
printf("%d temporary files deleted\n", rmtmp());
}
====================
...scanf functions
====================
Function| Header | Scans and formats input from...
---------+---------+-----------------------------------
cscanf | CONIO.H | The console
fscanf | STDIO.H | A stream
scanf | STDIO.H | stdin
sscanf | STDIO.H | A string
vfscanf | STDIO.H | A stream, using an argument list
vscanf | STDIO.H | stdin, using an argument list
vsscanf | STDIO.H | A string, using an argument list
Declaration:
* int cscanf ( char *format [, address, ...]);
* int fscanf (FILE *stream, const char *format [, address, ...]);
* int scanf ( const char *format [, address, ...]);
* int sscanf (const char *buffer, const char *format [, address, ...]);
* int vfscanf(FILE *stream, const char *format, va_list arglist);
* int vscanf ( const char *format, va_list arglist);
* int vsscanf(const char *buffer, const char *format, va_list arglist);
Remarks:
The ...scanf functions do the following:
* Scan a series of input fields one character at a time
* Format each field according to a corresponding format specifier passed
in the format string *format.
* Store the formatted input at an address passed as an argument following
*format (cscanf also echoes the input directly to the screen)
Argument| In Function(s) | What It Is/Does
---------+----------------+---------------------------------------------------
address | cscanf, fscanf |
| scanf, sscanf |
arglist | v...scanf | Pointer to a list of arguments
buffer | sscanf, vsscanf|
format | (all) | Format string
stream | fscanf,vfscanf |
The v...scanf functions are known as
alternate entry points for the ...scanf
functions.
They behave exactly like their ...scanf
counterparts, except they accept a pointer to
a list of arguments (va_list arglist) instead
of a list of arguments ([, address, ...]).
There must be one format specifier and
address for each input field.
A ...scanf function might stop scanning a
particular field before it reaches the normal
end-of-field (whitespace) character, or it
might terminate entirely.
For details about why this might happen, see
When ...scanf Functions Stop Scanning.
* WARNING: scanf often leads to unexpected
results if you diverge from an expected
pattern. You must teach scanf how to
synchronize at the end of a line.
The combination of gets or fgets followed by
sscanf is safe and easy, and therefore
recommended over scanf.
Return Value:
* On success, ...scanf functions return the number of input fields
successfully scanned, converted, and stored.
The return value does not include scanned fields that were not stored.
* Return value = 0 if no fields were stored.
* Return value = EOF if
* cscanf, fscanf, scanf, vfscanf, or vscanf attempts to read at
end-of-file, or
* sscanf or vsscanf attempts to read at end-of-string
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
cscanf | Yes | | | | |
fscanf | Yes | Yes | Yes | Yes | |
scanf | Yes | Yes | | Yes | |
sscanf | Yes | Yes | Yes | Yes | |
vfscanf | Yes | Yes | Yes | | |
vscanf | Yes | Yes | | | |
vsscanf | Yes | Yes | Yes | | |
+-----+------+---------+--------+----------+
See Also:
atof
fprintf
getc
getche
printf
va_arg
va_end
va_start
More ...scanf Topics
====================
Argument-type Modifiers
Assignment Suppression
Format Specifiers
Format Specifier Conventions
Format String
Input Fields
Pointer-size Modifiers
Type Characters
Width Specifiers
When ...scanf Functions Stop Scanning
Examples:
cscanf example
fscanf example
scanf example
sscanf example
vfscanf example
vscanf example
vsscanf example
cscanf example
================
#include <conio.h>
int main(void)
{
char string[80];
/* clear the screen */
clrscr();
/* Prompt the user for input */
cprintf("Enter a string with no spaces:");
/* read the input */
cscanf("%s", string);
/* display what was read */
cprintf("\r\nThe string entered is: %s", string);
return 0;
}
fscanf example
================
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int i;
printf("Input an integer: ");
/* read an integer from the
standard input stream */
if (fscanf(stdin, "%d", &i))
printf("The integer read was: %i\n", i);
else
{
fprintf(stderr, "Error reading an integer from stdin.\n");
exit(1);
}
return 0;
}
scanf example
===============
#include <stdio.h>
#include <conio.h>
int main(void)
{
char label[20];
char name[20];
int entries = 0;
int loop, age;
double salary;
struct Entry_struct
{
char name[20];
int age;
float salary;
} entry[20];
/* Input a label as a string of characters restricting to 20 characters */
printf("\n\nPlease enter a label for the chart: ");
scanf("%20s", label);
fflush(stdin); /* flush the input stream in case of bad input */
/* Input number of entries as an integer */
printf("How many entries will there be? (less than 20) ");
scanf("%d", &entries);
fflush(stdin); /* flush the input stream in case of bad input */
/* input a name restricting input to only letters upper or lower case */
for (loop=0;loop<entries;++loop)
{
printf("Entry %d\n", loop);
printf(" Name : ");
scanf("%[A-Za-z]", entry[loop].name);
fflush(stdin); /* flush the input stream in case of bad input */
/* input an age as an integer */
printf(" Age : ");
scanf("%d", &entry[loop].age);
fflush(stdin); /* flush the input stream in case of bad input */
/* input a salary as a float */
printf(" Salary : ");
scanf("%f", &entry[loop].salary);
fflush(stdin); /* flush the input stream in case of bad input */
}
/* Input a name, age and salary as a string, integer, and double */
printf("\nPlease enter your name, age and salary\n");
scanf("%20s %d %lf", name, &age, &salary);
/* Print out the data that was input */
printf("\n\nTable %s\n",label);
printf("Compiled by %s age %d $%15.2lf\n", name, age, salary);
printf("-----------------------------------------------------\n");
for (loop=0;loop<entries;++loop)
printf("%4d | %-20s | %5d | %15.2lf\n",
loop + 1,
entry[loop].name,
entry[loop].age,
entry[loop].salary);
printf("-----------------------------------------------------\n");
return 0;
}
sscanf example
================
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
char *names[4] = {"Peter", "Mike", "Shea", "Jerry"};
#define NUMITEMS 4
int main(void)
{
int loop;
char temp[4][80];
char name[20];
int age;
long salary;
/* clear the screen */
clrscr();
/* create name, age and salary data */
for (loop=0; loop < NUMITEMS; ++loop)
sprintf(temp[loop], "%s %d %ld", names[loop],
random(10) + 20,
random(5000) + 27500L);
/* print title bar */
printf("%4s | %-20s | %5s | %15s\n", "#", "Name", "Age", "Salary");
printf(" --------------------------------------------------\n");
/* input a name, age and salary data */
for (loop=0; loop < NUMITEMS; ++loop)
{
sscanf(temp[loop],"%s %d %ld", &name, &age, &salary);
printf("%4d | %-20s | %5d | %15ld\n", loop + 1, name, age, salary);
}
return 0;
}
vfscanf example
=================
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
FILE *fp;
int vfsf(char *fmt, ...)
{
va_list argptr;
int cnt;
va_start(argptr, fmt);
cnt = vfscanf(fp, fmt, argptr);
va_end(argptr);
return(cnt);
}
int main(void)
{
int inumber = 30;
float fnumber = 90.0;
char string[4] = "abc";
fp = tmpfile();
if (fp == NULL)
{
perror("tmpfile() call");
exit(1);
}
fprintf(fp,"%d %f %s\n",inumber,fnumber,string);
rewind(fp);
vfsf("%d %f %s",&inumber,&fnumber,string);
printf("%d %f %s\n",inumber,fnumber,string);
fclose(fp);
return 0;
}
vscanf example
================
#include <stdio.h>
#include <conio.h>
#include <stdarg.h>
int vscnf(char *fmt, ...)
{
va_list argptr;
int cnt;
printf("Enter an integer, a float, and a string (e.g. i,f,s,)\n");
va_start(argptr, fmt);
cnt = vscanf(fmt, argptr);
va_end(argptr);
return(cnt);
}
int main(void)
{
int inumber;
float fnumber;
char string[80];
vscnf("%d, %f, %s", &inumber, &fnumber, string);
printf("%d %f %s\n", inumber, fnumber, string);
return 0;
}
vsscanf example
=================
#include <stdio.h>
#include <conio.h>
#include <stdarg.h>
char buffer[80] = "30 90.0 abc";
int vssf(char *fmt, ...)
{
va_list argptr;
int cnt;
fflush(stdin);
va_start(argptr, fmt);
cnt = vsscanf(buffer, fmt, argptr);
va_end(argptr);
return(cnt);
}
int main(void)
{
int inumber;
float fnumber;
char string[80];
vssf("%d %f %s", &inumber, &fnumber, string);
printf("%d %f %s\n", inumber, fnumber, string);
return 0;
}
The ...scanf Format String
============================
The format string controls how each ...scanf
function scans, converts, and stores its
input fields.
The format string is a character string that
contains three types of objects:
* whitespace characters
* non-whitespace characters
* format specifiers
Whitespace Characters
=====================
The whitespace characters are blank, tab (\t)
or newline (\n).
If a ...scanf function encounters a
whitespace character in the format string,
it reads, but does not store, all consecutive
whitespace characters up to the next
non-whitespace character in the input.
Trailing whitespace is left unread (including
a newline), unless explicitly matched in the
format string.
Non-whitespace Characters
=========================
The non-whitespace characters are all other
ASCII characters except the percent sign (%).
If a ...scanf function encounters a
non-whitespace character in the format
string, it will read, but not store, a
matching non-whitespace character.
Format Specifiers
=================
The format specifiers direct the ...scanf
functions to read and convert characters
from the input field into specific types of
values, then store them in the locations
given by the address arguments.
Each format specifier must have an address
argument. If there are more format specs than
addresses, the results are unpredictable and
likely disastrous.
Excess address arguments (more than required
by the format) are ignored.
See Also:
Argument-type Modifiers
Assignment Suppression
Format Specifier Conventions
Format Specifiers
Input Fields
Pointer-size Modifiers
Type Characters
Width Specifiers
When ...scanf Functions Stop Scanning
...scanf Format Specifiers
============================
In ...scanf format strings, format specifiers
have the following form:
% [*] [width] [F|N] [h|l|L] type_char
Each format specifier begins with the percent
character (%).
After the % come the following, in this order:
Component| What It Is/Does
----------+---------------------------------------------------------------
[*] |(Optional) Assignment-suppression character
| Suppresses assignment of the next input field.
[width] |(Optional) Width specifier
| Specifies maximum number of characters to read; fewer
| characters might be read if the ...scanf function encounters
| a whitespace or unconvertible character.
[F|N] |(Optional) Pointer size modifier
| Overrides default size of address argument:
| N = near pointer
| F = far pointer
[h|l|L] |(Optional) Argument-type modifier
| Overrides default type of address argument:
| h = short int
| l = long int, if type_char specifies integer conversion
| l = double, if type_char specifies floating-point conversion
| L = long double, (valid only with floating-point conversion)
type_char|(Required) Type character
See Also:
Format Specifier Conventions
Format String
Input Fields
When ...scanf Functions Stop Scanning
...scanf Type Characters
==========================
The information in this table is based on the
assumption that no optional characters,
specifiers, or modifiers (*, width, or size)
were included in the format specifier.
* NOTE: Certain conventions accompany some of
these format specifiers.
Type | |
Char | Expected input | Type of argument
-------+--------------------+---------------------------------------------
Numerics
-------+--------------------+---------------------------------------------
d | Decimal integer | Pointer to int (int *arg)
D | Decimal integer | Pointer to long (long *arg)
e, E | Floating point | Pointer to float (float *arg)
f | Floating point | Pointer to float (float *arg)
g, G | Floating point | Pointer to float (float *arg)
o | Octal integer | Pointer to int (int *arg)
O | Octal integer | Pointer to long (long *arg)
i | Decimal, octal, or | Pointer to int (int *arg)
| hexadecimal integer|
I | Decimal, octal, or | Pointer to long (long *arg)
| hexadecimal integer|
u | Unsigned decimal | Pointer to unsigned int
| integer | (unsigned int *arg)
U | Unsigned decimal | Pointer to unsigned long
| integer | (unsigned long *arg)
x | Hexadecimal integer| Pointer to int (int *arg)
X | Hexadecimal integer| Pointer to int (int *arg)
-------+--------------------+---------------------------------------------
Characters
-------+--------------------+---------------------------------------------
s | Character string | Pointer to array of chars (char arg[])
c | Character | Pointer to char (char *arg) if a field width
| | W is given along with the c-type character
| | (such as %5c)
| | Pointer to array of W chars (char arg[W])
% | % character | No conversion done; the % is stored
-------+--------------------+---------------------------------------------
Pointers
-------+--------------------+---------------------------------------------
n | | Pointer to int (int *arg). The number
| | of characters read successfully up to %n
| | is stored in this int.
p | Hexadecimal form | Pointer to an object (far* or near*)
| YYYY:ZZZZ or | %p conversions default to the pointer
| ZZZZ | size native to the memory model
See Also:
Argument-type Modifiers
Assignment Suppression
Format Specifier Conventions
Format Specifiers
Format String
Input Fields
Pointer-size Modifiers
Width Specifiers
When ...scanf Functions Stop Scanning
Input Fields for ...scanf Functions
=====================================
In a ...scanf function, any one of the
following is an input field:
* all characters up to (but not including)
the next whitespace character
* all characters up to the first one that
can't be converted under the current
format specifier (such as an 8 or 9 under
octal format)
* up to n characters, where n is the
specified field width
See Also:
Argument-type Modifiers
Assignment Suppression
Format Specifier Conventions
Format Specifiers
Format String
Pointer-size Modifiers
Type Characters
Width Specifiers
When ...scanf Functions Stop Scanning
...scanf Assignment-suppression Character
===========================================
The assignment-suppression character is an
asterisk (*), not to be confused with the C
indirection (pointer) operator.
If the asterisk follows the percent sign (%)
in a format specifier, the next input field
will be scanned but it won't be assigned to
the next address argument.
The suppressed input data is assumed to be of
the type specified by the type character that
follows the asterisk character.
See Also:
Argument-type Modifiers
Format Specifier Conventions
Format Specifiers
Format String
Input Fields
Pointer-size Modifiers
Type Characters
Width Specifiers
When ...scanf Functions Stop Scanning
...scanf Width Specifiers
===========================
The width specifier (n), a decimal integer,
controls the maximum number of characters
to be read from the current input field.
Up to n characters are read, converted, and
stored in the current address argument.
If the input field contains fewer than n
characters, the ...scanf function reads all
the characters in the field, then proceeds
with the next field and format specifier.
The success of literal matches and suppressed
assignments is not directly determinable.
If the ...scanf function encounters a
whitespace or nonconvertible character before
it reads "width" characters, it:
* reads, converts, and stores the characters
read so far, then
* attends to the next format specifier.
A nonconvertible character is one that can't
be converted according to the given format
(8 or 9 when the format is octal, J or K when
the format is hexadecimal or decimal, etc.).
See Also:
Argument-type Modifiers
Assignment Suppression
Format Specifier Conventions
Format Specifiers
Format String
Input Fields
Pointer-size Modifiers
Type Characters
When ...scanf Functions Stop Scanning
...scanf Pointer-size and Argument-type Modifiers
===================================================
These modifiers affect how ...scanf functions
interpret the corresponding address argument
arg[f].
Pointer-size Modifiers
======================
Pointer-size modifiers override the default
or declared size of arg.
Mod| arg Interpreted As...
----+-----------------------------------
F | Far pointer
N | Near pointer (Can't be used with
| any conversion in huge model)
Argument-type Modifiers
=======================
Argument-type modifiers indicate which type
of the following input data is to be used
(h = short, l = long, L = long double).
The input data is converted to the specified
version, and the arg for that input data
should point to an object of corresponding
size.
Mod| For This Type| Convert Input to...
----+--------------+-------------------------------------------
h | d i o u x | short int; store in short object
| D I O U X | (No effect)
| e f c s n p | (No effect)
l | d i o u x | long int; store in long object
| e f g | double; store in double object
| D I O U X | (No effect)
| c s n p | (No effect)
L | e f g | long double; store in long double object
| (all others) | (No effect)
See Also:
Assignment Suppression
Format Specifier Conventions
Format Specifiers
Format String
Input Fields
Type Characters
Width Specifiers
When ...scanf Functions Stop Scanning
...scanf Format Specifier Conventions
=======================================
Certain conventions accompany some of the
...scanf format specifiers.
Choose one of the following Help hot links
for information about conventions for the
following conversions:
* single character (%c)
* character array (%[W]c)
* string (%s)
* floating-point (%e, %E, %f, %g, and %G)
* unsigned (%d, %i, %o, %x, %D, %I, %O, %X, %c, %n)
See Also:
Argument-type Modifiers
Assignment Suppression
Format Specifiers
Format String
Input Fields
Pointer-size Modifiers
Type Characters
Width Specifiers
When ...scanf Functions Stop Scanning
Single Character Conversion
=============================
%c
This specification reads the next character,
including a whitespace character.
To skip one whitespace character and read the
next non-whitespace character, use %1s.
Character Array Conversion
============================
%[W]c
[W] = width specification
The address argument is a pointer to an array
of characters (char arg[W]).
The array consists of W elements.
String Conversion
===================
%s
The address argument is a pointer to an array
of characters (char arg[]).
The array size must be at least (n+1) bytes,
where
n = the length of string s (in characters).
A space or newline character terminates the
input field.
A null terminator is automatically appended
to the string and stored as the last element
in the array.
Floating-point Conversions
============================
%e, %E, %f, %g, and %G
Floating-point numbers in the input field
must conform to the following generic format:
[+/-] ddddddddd [.] dddd [E|e] [+/-] ddd
where [item] indicates that item is optional,
and ddd represents digits (decimal, octal, or
hexadecimal).
In addition, +INF, -INF, +NAN, and -NAN are
recognized as floating-point numbers. The
sign (+ or -) and capitalization are
required.
Unsigned Conversions
======================
%d, %i, %o, %x, %D, %I, %O, %X, %c, and %n
A pointer to unsigned character, unsigned
integer, or unsigned long can be used in any
conversion where a pointer to a character,
integer, or long is allowed.
When ...scanf Functions Stop Scanning
=======================================
A ...scanf function might stop scanning a
particular input field before reaching the
normal field-end character (whitespace), or
it might terminate entirely.
Stop and Skip to Next Input Field
=================================
...scanf functions stop scanning and storing
the current input field and proceed to the
next one if any of the following occurs:
* An assignment-suppression character (*)
appears after the % in the format specifier.
The current input field is scanned but not stored.
* width characters have been read.
* The next character read can't be converted
under the current format (for example, an A
when the format is decimal).
* The next character in the input field does
not appear in the search set (or does appear
in an inverted search set).
When scanf stops scanning the current input
field for one of these reasons, it assumes
that the next character is unread and is
either
* the first character of the following input
field, or
* the first character in a subsequent read
operation on the input.
Terminate
=========
...scanf functions will terminate under the
following circumstances:
* The next character in the input field
conflicts with a corresponding non-whitespace
character in the format string.
* The next character in the input field is EOF.
* The format string has been exhausted.
If a character sequence that is not part of
a format specifier occurs in the format
string, it must match the current sequence of
characters in the input field.
...scanf functions will scan but not store
the matched characters.
When a conflicting character occurs, it
remains in the input field as if the ...scanf
function never read it.
See Also:
Argument-type Modifiers
Assignment Suppression
Format Specifier Conventions
Format Specifiers
Format String
Input Fields
Pointer-size Modifiers
Type Characters
Width Specifiers
=================
setbuf, setvbuf <STDIO.H>
=================
Assigns buffering to a stream
Declaration:
* void setbuf(FILE *stream, char *buf);
* int setvbuf(FILE *stream, char *buf, int type, size_t size);
Remarks:
setbuf and setvbuf cause the buffer buf to
be used for I/O buffering, instead of an
automatically allocated buffer.
* With setbuf, if buf is null, I/O will be
unbuffered. Otherwise, it will be fully
buffered. The setbuf buffer must be BUFSIZ
bytes long.
* With setvbuf, if buf is null, a buffer will
be allocated using malloc. The setvbuf buffer
will use size as the amount allocated and
will be automatically freed on close.
Argument | What It Is/Does
----------+----------------------------------------------------------------
stream | Stream to which buffering is assigned
buf | Points to a buffer to be used for I/O buffering. The buffer is
| used after stream has been opened.
type | One of the buffer-type _IO... defines _IOFBF, _IOLBF, or _IONBF
size | Specifies the setvbuf buffer size. 0 < size < 32,767
stdin and stdout are unbuffered if they are
not redirected. Otherwise, they are fully
buffered. setbuf can be used to change the
buffering style being used.
* NOTE: setbuf produces unpredictable results
unless it is called immediately after opening
stream or after a call to fseek. Calling
setbuf after stream has been unbuffered is
legal and will not cause problems.
* NOTE: A common cause for error is to
allocate the buffer as an automatic (local)
variable and then fail to close the file
before returning from the function where the
buffer was declared.
Unbuffered vs. Buffered
=======================
Unbuffered means that characters written to a
stream are immediately output to the file or
device.
Buffered means that the characters are
accumulated and written as a block.
Return Value:
* setbuf does not return.
* On success, setvbuf returns 0.
* On error, setvbuf returns non-zero (if an
invalid value is given for type or size,
or if there is not enough space to
allocate a buffer)
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | Yes | |
+-----+------+---------+--------+----------+
See Also:
fflush
fopen
fseek
Examples:
setbuf example
setvbuf example
setbuf example
================
#include <stdio.h>
/* BUFSIZ is defined in stdio.h */
char outbuf[BUFSIZ];
int main(void)
{
/* attach a buffer to the standard output stream */
setbuf(stdout, outbuf);
/* put some characters into the buffer */
puts("This is a test of buffered output.\n\n");
puts("This output will go into outbuf\n");
puts("and won't appear until the buffer\n");
puts("fills up or we flush the stream.\n");
/* flush the output buffer */
fflush(stdout);
return 0;
}
setvbuf example
=================
#include <stdio.h>
int main(void)
{
FILE *input, *output;
char bufr[512];
input = fopen("file.in", "r+b");
output = fopen("file.out", "w");
/* set up input stream for minimal disk access,
using our own character buffer */
if (setvbuf(input, bufr, _IOFBF, 512) != 0)
printf("failed to set up buffer for input file\n");
else
printf("buffer set up for input file\n");
/* set up output stream for line buffering using space that
will be obtained through an indirect call to malloc */
if (setvbuf(output, NULL, _IOLBF, 132) != 0)
printf("failed to set up buffer for output file\n");
else
printf("buffer set up for output file\n");
/* perform file I/O here */
/* close files */
fclose(input);
fclose(output);
return 0;
}
=========
tempnam <STDIO.H>
=========
Creates a unique file name in specified directory.
Declaration: char *tempnam(char *dir, char *prefix)
Remarks
tempnam creates a unique file name in
arbitrary directories.
It attempts to use the following directories,
in the order shown, when creating the file:
1) The directory specified by the TMP environment variable.
2) The dir argument to tempnam.
3) The P_tmpdir definition in STDIO.H. If you edit STDIO.H and
change this definition, tempnam will NOT use the new definition.
4) The current working directory.
Argument| What It Does
--------+---------------------------------------------------------------
dir | Specifies the directory where the file will be created
prefix | Specifies the first part of the file name; it can't be longer
| than 5 characters, and may not contain a period (.)
If any of these directories is NULL,
undefined, or does not exist, it is skipped.
tempnam creates a unique file name by
concatenating the directory name, the prefix,
and 6 unique characters.
Space for the resulting file name is
allocated with malloc; the caller should call
free to free this file name when it's no
longer needed.
The unique file is not actually created;
tempnam only verifies that it does not
currently exist.
Return Value:
* On success, returns a pointer to the temporary file name.
* Returns NULL if it can't create a unique file name.
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | | |
+-----+------+---------+--------+----------+
See Also:
Deleting the temporary file name
mktemp
tmpfile
tmpnam
Example
#include <stdio.h>
#include <stdlib.h>
void main(void)
{
FILE *stream;
int i;
char *name;
for (i = 1; i <= 10; i++) {
if ((name = tempnam("\\tmp","wow")) == NULL)
perror("tempnam couldn't create name");
else {
printf("Creating %s\n",name);
if ((stream = fopen(name,"wb")) == NULL)
perror("Could not open temporary file\n");
else
fclose(stream);
}
free(name);
}
printf("Warning: temp files not deleted.\n");
}
Deleting the temporary file name
(created by tempnam or tmpnam)
==================================
If you do create a temporary file using the
name constructed by tempnam or tmpnam, it is
your responsibility to delete the file name
(for example, with a call to remove).
It is not deleted automatically. (tmpfile
does delete the file name.)
=========
tmpfile <STDIO.H>
=========
Opens a "scratch" file in binary mode
Declaration: FILE *tmpfile(void);
Remarks:
tmpfile creates a temporary binary file and
opens it for update (w + b).
The file is automatically removed when it's
closed or when your program terminates.
Return Value:
* On success, tmpfile returns a pointer to
the stream of the temporary file created.
* On error (if the file can't be created),
tmpfile returns null.
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | Yes | |
+-----+------+---------+--------+----------+
See Also:
fopen
tempnam
tmpnam
Example:
#include <stdio.h>
#include <process.h>
int main(void)
{
FILE *tempfp;
tempfp = tmpfile();
if (tempfp)
printf("Temporary file created\n");
else
{
printf("Unable to create temporary file\n");
exit(1);
}
return 0;
}
========
tmpnam <STDIO.H>
========
Creates a unique file name
Declaration: char *tmpnam(char *sptr);
Remarks:
tmpnam creates a unique file name, which can
safely be used as the name of a temporary
file.
tmpnam generates a different string each time
you call it, up to TMP_MAX times.
sptr is either null or a pointer to an array
of at least L_tmpnam characters.
* If sptr is null, tmpnam leaves the temporary file name in an
internal static object and returns a pointer to that object.
* If sptr is not null, tmpnam places the temporary file name in
the array *sptr and returns sptr.
Return Value:
* If sptr is null, returns a pointer to an internal static object.
* If sptr is not null, returns sptr.
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | Yes | |
+-----+------+---------+--------+----------+
See Also:
Deleting the temporary file name
tempnam
tmpfile
Example:
#include <stdio.h>
int main(void)
{
char name[13];
tmpnam(name);
printf("Temporary name: %s\n", name);
return 0;
}
========
ungetc <STDIO.H>
========
Pushes a character back into input stream
Declaration: int ungetc(int c, FILE *stream);
Remarks:
ungetc pushes the character c back onto the
named input stream, which must be open for
reading.
This character will be returned on the next
call to getc or fread for that stream.
One character can be pushed back in all
situations.
A second call to ungetc without a call to
getc will force the previous character to be
forgotten.
A call to fflush, fseek, fsetpos, or rewind
erases all memory of any pushed-back
characters.
Return Value
* On success, ungetc returns the character pushed back.
* On failure, ungetc returns EOF.
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | Yes | |
+-----+------+---------+--------+----------+
See Also:
fgetc
getc
getchar
Example:
#include <stdio.h>
#include <ctype.h>
int main( void )
{
int i=0;
char ch;
puts("Input an integer followed by a char:");
/* read chars until non digit or EOF */
while((ch = getchar()) != EOF && isdigit(ch))
i = 10 * i + ch - 48; /* convert ASCII into int value */
/* if non digit char was read, push it back into input buffer */
if (ch != EOF)
ungetc(ch, stdin);
printf("i = %d, next char in buffer = %c\n", i, getchar());
return 0;
}