Runtime Library Reference
· Constants
· Data types
Standard C
· assert.h
· complex.h
· ctype.h
· fenv.h
· float.h
· locale.h
· math.h
· setjmp.h
· signal.h
· stdarg.h
· stddef.h
· stdio.h
· stdlib.h
· string.h
· time.h
Standard C++
· IOstream
· new
Win32
· gc.h
DOS, DOS32, Win16
· bios.h
· cerror.h
· disp.h
· dos.h
· dos.h part 2
· emm.h
· handle.h
· int.h
· msmouse.h
· sound.h
· swap.h
· tsr.h
· winio.h
Other C
· bitops.h
· conio.h
· controlc.h
· direct.h
· fltpnt.h
· io.h
· page.h
· process.h
· search.h
· sys\stat.h
· tabsize.h
· trace.h
· utime.h
· unmangle.h
· util.h
Other C++
· regexp.h
· class complex
|
stdio.h
Stdio is the header for the standard functions that deal with input and output
to the console and to files.
- Header
- stdio.h
- Prototype
- int _fcloseall(void);
- Description
- The _fcloseall function closes all open streams and files except
stderr, stdin, and stdout. Any data in the I/ O buffers is flushed
before closing.
- Synonym
- Function: fcloseall
- Return Value
- The number of streams closed. Returns EOF If an error occurs.
- Compatibility
- DOS Windows 3.x Phar Lap DOSX Win32
- See Also
- _close
fclose
fopen
- Example
/* Example for _fcloseall and fopen */
#include <stdio.h>
#include <stdlib.h>
int main()
{
int closed_count;
FILE *pfile1, *pfile2;
pfile1 = fopen("temp.dat", "w+");
pfile2 = fopen("temp2.dat", "w+");
if ((pfile1 == NULL) || (pfile2 == NULL))
perror("A data file could not be opened");
else
{
closed_count = _fcloseall();
printf("Fcloseall closed %d streams\n",
closed_count);
}
return EXIT_SUCCESS;
}
- Output
Fcloseall closed 2 streams
- Header
- stdio.h
- Prototype
- FILE *_fdopen(int fd, const char *mode);
- Description
-
_fdopen allows a file that has been open for low-level,
unbuffered I/O (with open) to be associated with an input/output
stream. When the file is associated with a stream, it can be
buffered and formatted.
The handle of the already opened file is passed as fd
and the file mode is pointed to by mode.
If the specified mode is an append
mode, the file pointer is positioned at the end of the file, otherwise
the file pointer is positioned at the beginning of the file. If the
specified mode is a write mode, the file is truncated. No checking is
done to assure that the mode of the buffered file is compatible with
the mode of the unbuffered file. Incompatibility of file modes will
give undefined results.
The values for mode are:
| Value | Meaning |
| "r" |
Read only. |
| "w" |
Write only with truncation; existing contents are destroyed. |
| "a" |
Write only with append. |
| "r+" |
Read and write. |
| "w+" |
Read and write with truncatation; existing
contents are destroyed. |
| "a+" |
Read and write with append. |
Values that can be appended to the mode are:
| t |
Open in text (translated) mode. |
| b |
Open in binary (untranslated) mode. |
- Synonym
-
Function: fdopen
- Return Value
-
A FILE pointer to opened file. NULL is returned is the file could not
be opened with buffering.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
_open
fopen
- Example
/* Example for _fdopen
Also demonstrates open, fgets
*/
#include <dos.h>
#include <fcntl.h>
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int fd;
FILE *fp;
char line[81];
fd = open("temp.dat", O_RDONLY);
if (fd == -1)
perror("Error opening file");
else
{
fp = _fdopen(fd, "r");
if (fp == NULL)
perror("Error opening file for read");
else
{
fgets(line, 80, fp);
printf("The first line of temp.dat is:\n%s\n", line);
}
}
}
- Output
The first line of temp.dat is:
This is an example.
- Header
-
stdio.h
- Prototype
-
int _fgetchar(void);
- Description
-
_fgetchar reads a single character from stdin. The
character is converted and returned as an integer.
- Synonym
-
Function: fgetchar
- Return Value
-
The character that was read. Returns EOF if an error or end-of-file is
encountered.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fputc
getc
getchar
- Example
/* Example for _fgetchar */
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
printf("Enter a character followed by ret:\n");
ch = _fgetchar();
printf("The character read from stdin is : %c\n", ch);
}
- Output
Enter a character followed by ret: j
The character read from stdin is : j
- Header
-
stdio.h
- Prototype
-
int _fileno(FILE *fp);
- Description
-
Returns the file descriptor associated with stream fp. The fp
argument must point to a file which is already open. The fileno
function converts a file pointer to a file descriptor for use with the
low-level file functions such as close, read, and write. Mixing of
high and low level functions is not recommended.
- Synonym
-
Function: fileno
- Return Value
-
Returns the file descriptor; no error return.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fopen
freopen
- Example
/* Example for _fileno */
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("The handle for stdin is %d\n",
_fileno(stdin));
printf("The handle for stdout is %d\n",
_fileno(stdout));
printf("The handle for stderr is %d\n",
_fileno(stderr));
}
- Output
The handle for stdin is 0
The handle for stdout is 1
The handle for stderr is 2
- Header
-
stdio.h
- Prototype
-
int _flushall(void);
- Description
-
The _flushall function flushes the I/O buffers for all open
streams. Output buffers are written to their associated files and input
buffers are cleared. All streams remain open after a call to
_flushall. Any read operation reads new data into the buffers.
- Synonym
-
Function: flushall
- Return Value
-
The number of open streams.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fflush
- Example
/* Example for _flushall */
#include <stdio.h>
#include <stdlib.h>
int main()
{
int tf;
tf = _flushall ();
printf("%d streams flushed\n", tf);
}
- Output
5 streams flushed
- Header
-
stdio.h
- Prototype
-
int _fputchar(int c);
- Description
-
The _fputchar function is equivalent to fputc, except that
_fputchar writes the character to standard output.
- Synonym
-
Function: fputchar
- Return Value
-
The last character output to the stream. An EOF is returned on error.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fgetc
fputc
getchar
- Example
/* Example for fputchar */
#include <stdio.h>
int main()
{
char *str = "All the king's horses and all
the king's men", *ptr;
ptr = str;
while (* ptr && (fputchar(*(ptr++)) != EOF));
}
- Output
All the king's horses and all the king's men
- Header
-
stdio.h
share. h
- Prototype
-
FILE *_fsopen(const char *filename, const char *mode, int shflag);
- Description
-
The _fsopen function opens filename as a stream and returns
the associated stream pointer. The mode argument specifies the type
of access that is allowed; the shflag argument specifies the sharing
mode. Values for the mode argument are:
- Value/Meaning
- "r"
- Read only; file must exist or call will fail.
- "w"
- Write only and truncate; if file exists, existing contents
are destroyed.
- "a"
- Write only and append; if file does not exist, it is created.
- "r+"
- Read and write; file must exist or call will fail.
- "w+"
- Read, write, and truncate; if file exists, existing contents
are destroyed.
- "a+"
- Read, write, and append; if file does not exist, it is
created.
Values that can be appended to the mode argument are:
- t
- Open in text (translated) mode.
- b
- Open in binary (untranslated) mode
The following values can be specified for the shflag argument and
are are defined in share. h. If share.com (or share. exe, for
some DOS versions) is not installed, shflag is ignored.
- _SH_COMPAT
- Sets compatibility mode
- _SH_DENYNO
- Permits read and write access
- _SH_DENYRD
- Denies read access to file
- _SH_DENYRW
- Denies read and write access to file
- _SH_DENYWR
- Denies write access to the file
A pointer to the stream. A NULL pointer value indicates an error.
- Return Value
-
A pointer to the stream. A NULL pointer value indicates an error.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fclose
_fcloseall
_fdopen
fopen
freopen
_open
_setmode
_sopen
- Example
/* Example of _fsopen */
#include <dos.h>
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <share.h>
int main()
{
FILE *fp;
char fn[_MAX_PATH];
printf("Enter a filename: ");
gets(fn);
if ((fp = _fsopen(fn, "r", _SH_DENYRW)) ==
NULL)
{
perror("Cannot open file");
exit (EXIT_FAILURE);
}
printf("File opened successfully, no one
else can read or write to it.\n");
fclose(fp);
}
- Output
Enter a filename: _fsopen.c
File opened successfully, no one else can read
or write to it.
- Header
-
stdio.h
- Prototype
-
int _getw(FILE *stream);
- Description
-
The _getw function returns the next binary value of type int from
the file associated with the stream argument. The file pointer is
incremented to point to the next unread character. Do not use this
function on a file that was opened in text mode.
- Synonym
-
Function: getw
- Return Value
-
The next integer in the file. If an error occurs or the end-of-file is
read, EOF is returned.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
_putw
- Example
/* Example for _getw
Also demonstrates _putw, fopen, fclose, rand
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int n, i;
fp = fopen("testfile", "wb");
if (fp == NULL)
{
perror("Couldn't open TESTFILE to write");
exit (EXIT_FAILURE);
}
printf("Writing ");
for (i = 10; i > 0; i -= 1)
{
n = rand ();
printf("%d ", n);
_putw (n, fp);
}
printf("\n");
fclose(fp);
fp = fopen("testfile", "rb");
if (fp == NULL)
{
perror("Couldn't open TESTFILE to read");
exit (EXIT_FAILURE);
}
printf("Read ");
for (;;)
{
n = _getw(fp);
if (n == EOF)
break;
printf("%d ", n);
}
printf("\n");
fclose(fp);
}
- Output
Writing 16838 5758 10113 17515 31051 5627 23010
7419 16212 4086
Read 16838 5758 10113 17515 31051 5627 23010
7419 16212 4086
- Header
-
tsr.h
- Prototype
- extern int _okbigbuf;
- Description
-
This variable, used in T and S Memory Models only, defines which
memory allocation method to use:
° Allocate all available memory up to 64 KB to the heap
upon program startup. This is the default method.
° Allocate memory to the heap only as needed. Use this
method if a spawn function will be needed. To use,
declare _okbigbuf as shown below. For more
information, see the Compiler and Tools Guide.
To prevent the allocation of memory, re-declare _okbigbuf as:
int _okbigbuf = 0;
_okbigbuf != 0 signifies that large disk buffers are used for
stream I/ O outside the data segment.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- Header
-
stdio.h
- Prototype
-
int _putw(int binint, FILE *stream);
- Description
-
The _putw function writes the binary value stored in the binint
argument to the current position of the stream argument. The
function does not affect the alignment of items in the stream.
Portability problems can occur with the _putw function because the
size of an int and ordering of bytes within an int can vary across
systems.
- Synonym
-
Function: putw
- Return Value
-
Both functions return the value that is written. If an error occurs,
EOF is returned. EOF may also be a legitimate integer value.
Therefore, use ferror to verify an error.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
_getw
- Example
-
See getw
- Header
-
stdio.h
- Prototype
-
int _rmtmp(void);
- Description
-
The _rmtmp function closes and deletes all temporary files created
by tmpfile in the current directory. The current directory must be
the same directory in which the files were created.
- Return Value
-
The number of temporary files closed and deleted.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
_flushall
tmpfile
tmpnam
- Example
/* Example of _rmtmp */
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int i;
for (i = 1; i <= 10; i++)
if ((fp = tmpfile ()) == NULL)
perror("Could not open temp file");
else
printf("Temp file %d created\n", i);
i = _rmtmp ();
printf("Removed %d temp files\n", i);
}
- Output
Temp file 1 created
Temp file 2 created
Temp file 3 created
Temp file 4 created
Temp file 5 created
Temp file 6 created
Temp file 7 created
Temp file 8 created
Temp file 9 created
Temp file 10 created
Removed 10 temp files
- Header
-
stdio.h
- Prototype
- extern File *_stdaux;
- Description
-
_stdaux is a constant FILE pointer to the standard auxiliary stream, which is usually the first serial port. I/ O through _stdaux is usually
unbuffered
- Synonym
-
stdaux
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
stderr
stdin
stdout
_stdprn
- Header
-
stdio.h
- Prototype
- extern FILE *_stdprn;
- Description
-
_stdprn is a constant FILE pointer to the standard print stream, which is usually the first parallel port. I/ O through _stdaux is usually unbuffered.
- Synonym
-
stdprn
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
_stdaux
stderr
stdin
stdout
- Header
-
stdio.h
- Prototype
-
char *_tempnam(char *dir, char *prefix);
- Description
-
The _tempnam function generates a unique temporary filename that
is valid, but not the same as, the name of any existing file. The
function is similar to tmpnam, except the string returned is always
malloc'ed. The dir argument is the directory in which to create
the temporary file. If dir is NULL, the current directory specified by
the P_tmpdir constant is used. The prefix argument is a 5
character prefix string used for the start of the temporary filename.
- Synonym
-
Function: tempnam
- Return Value
-
A malloc'ed string containing the temporary file name. If tempnam
is unable to create the temporary filename for any reason a NULL
pointer is returned.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
tmpnam
- Example
/* Example for _tempnam */
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *name;
if ((name = _tempnam (NULL, "abcde")) == NULL)
{
perror("Unable to create temporary filename");
exit (EXIT_FAILURE);
}
printf("Temporary filename \"%s\"
created.\n", name);
free (name);
}
- Output
Temporary filename "abcdeCCE. tmp" created.
- Header
-
stdio.h
- Prototype
-
void clearerr(FILE *fp);
- Description
-
The clearerr function clears error and EOF (end-of-file) flags associated with the stream fp. Once the error flag on a stream is set, any operation carried out on that stream will return an error status unless a call is made to clearerr. Flag EOF is cleared with each input from the stream.
- Return Value
-
None
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
feof
ferror
- Example
/* Example for clearerr */
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *stream;
char *string = "Sample Data";
stream = fopen("temp.dat", "r");
fprintf(stream, "%s\n", string);
if (ferror(stream))
{
printf("Write File Error");
clearerr(stream);
fclose(stream);
}
else
{
printf("No error writing to stream");
fclose(stream);
}
}
- Output
Write File Error
- Header
-
stdio.h
- Prototype
-
int fclose(FILE *fp);
- Description
-
fclose closes the file associated with the stream fp. Any data in
the output buffer for fp is flushed (written to the file) before closing.
- Return Value
-
fclose returns 0 if the stream successfully closed. A -1 is returned
on error.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
_close
fopen
freopen
- Example
/* Example for fclose Also demonstrates fopen
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *pfile;
pfile = fopen("temp.dat", "w+");
if (pfile == NULL)
perror("Data file not opened");
else
{
fclose(pfile);
printf("Data file closed using fclose\n");
}
}
- Output
Data file closed using fclose
- Header
-
stdio.h
- Prototype
-
int feof(FILE *fp);
- Description
-
feof determines if the stream fp is at the end of file. After the EOF
indicator is set no further read operations are allowed.
- Return Value
-
Returns non-zero if current position is at the end of the file (which
sets the EOF flag in the FILE structure). No read operations are
allowed after the flag is set. The flag is cleared if rewind or fseek
are called, or when the file is closed. Returns 0 if the the EOF flag is
not set.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
clearerr
ferror
- Example
/* Example for feof Also demonstrates fopen, fgets
*/
#include <stdio.h>
#include <stdlib.h>
#define BUFSIZE 128
char buffer[BUFSIZE];
int main()
{
FILE *fp;
fp = fopen("temp.dat", "r");
if (fp != NULL)
{
while (! feof(fp))
{
fgets (buffer, BUFSIZE, fp);
printf("%s", buffer);
}
}
else
perror("Error opening file");
}
- Output
This program types the contents of temp.dat to the screen.
- Header
-
stdio.h
- Prototype
-
int ferror(FILE *fp);
- Description
-
ferror checks the error flag on the stream fp. The error flag
remains set until a call to clearerr, or rewind is issued, or the
stream is closed. No read or write operations can be carried out until
this flag is cleared.
- Return Value
-
Returns non-zero if the error flag is set. Otherwise it returns a zero.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
clearerr
feof
- Example
/* Example for ferror Also demonstrates clearerr
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
fp = fopen("temp.dat", "r");
if (fp != NULL)
{
fputs("This is a write error\n", fp);
if (ferror(fp))
{
printf("Stream i/o error");
clearerr(fp);
}
fclose(fp);
}
else
perror("Error opening file");
}
- Output
Stream i/o error
- Header
-
stdio.h
- Prototype
-
int fflush(FILE *fp);
- Description
-
Flushes the buffer associated with stream fp. If fp is NULL, fflush
flushes the buffers for all open streams. If the file is opened for
writing, the buffer is written. If the file is opened for reading, the
buffer is cleared. The fflush function may be used to force the
data in the file buffer to be written to the file before the buffer
becomes full. Similarly data read from a file is input a buffer full at a time. Only after every character has been processed does another
file access occur. The fflush function may be used to clear the
buffer and thus force the next read operation to occur.
- Return Value
-
0 if the buffer is successfully flushed. Returns EOF if an error occurs.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fclose
_flushall
- Example
/* Example for fflush */
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
fp = fopen("temp.dat", "w");
fflush(fp);
/* Flush buffer to disk to protect data
before performing operations that can
cause system crash
*/
fclose(fp);
}
- Output
This program produces no output.
- Header
-
stdio.h
- Prototype
-
int fgetc(FILE *fp);
- Description
-
fgetc reads and returns the next character from the stream fp. The
character is returned as an integer in the range of 0 to 255.
- Return Value
-
Returns the character just read on success, or EOF if end-of-file or a
read error is encountered. The return value must always be assigned
to a variable of type int, or an error cannot be detected (as EOF is
negative).
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fputc
putchar
getc
getchar
_getche
_getch
- Example
/* Example for fgetc, fputc */
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int input;
fp = fopen("temp.dat"," w+");
if (fp!= NULL)
{
printf("Enter data terminated by
ctrl-z:");
while ((input = fgetc (stdin)) != EOF)
{
printf("%c",(char) input);
fputc (input, fp);
}
fclose(fp);
}
else
perror("Error opening temp file");
}
- Output
-
This program will echo keyboard input to the screen and put it in the file temp.dat. The program output looks like this:
Enter data terminated by ctrl-z: Hello from
Digital Mars
Hello from Digital Mars
^Z
- Header
-
stdio.h
- Prototype
-
int fgetpos(FILE *fp, fpos_t *pos);
- Description
-
The function fgetpos gets the current position of the stream fp.
The position is stored in pos.
- Return Value
-
Returns 0 if successful, otherwise returns non-zero with errno set.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fsetpos
- Example
/* Example for fgetpos, fsetpos Also demonstrates
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
fpos_t fpos;
char dump[64];
fp = fopen("temp.dat", "r");
fread(dump, 1, 64, fp);
/* save current position */
if (fgetpos (fp, &fpos) != 0)
perror("fgetpos failed");
fread(dump, 1, 64, fp);
/* back to previous position*/
if (fsetpos (fp, &fpos) != 0)
perror("fsetpos failed"); fclose(fp);
}
- Output
This program produces no output.
- Header
-
stdio.h
- Prototype
-
char *fgets(char *str, int n, FILE *fp);
- Description
-
Reads characters from stream fp into the string pointed to by str.
The integer argument n indicates the maximum number of
characters that the buffer str can store. Reading stops when a
newline is read, end-of-file is encountered, a read error occurs, or n-1
characters were read. Newlines are included in the string. The
string read is terminated with a 0.
- Return Value
-
String str if successful. If no characters have been read into str
and a read error or EOF is encountered, NULL is returned and the
string pointed to by str is unchanged. If a read error occurs, NULL
is returned and str contains garbage.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fputs
gets
puts
- Example
/* Example for fgets Also demonstrates
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
char buffer[255];
int buflen;
char *result;
buflen = 255;
printf("Enter line of data:\n");
result = fgets (buffer, buflen, stdin);
if (result == NULL)
printf("\nEOF or Error\n");
else
printf("The input was :\n%s\n", buffer);
}
- Output
-
Enter line of data:
The quick brown fox jumped over the lazy dog.
The input was :
The quick brown fox jumped over the lazy dog.
- Prototype
-
FILE *fopen(char *name, char *mode);
- Description
-
fopen opens a file. name gives the filename to be opened. mode is
a character string indicating how the file is to be opened. Possible
values for mode are:
- "r"
- for reading
- "w"
- for writing (truncates any existing file with the same
- name)
- "a"
- for appending (if file exists then open for writing at
- end of file, else create the file)
- "r+"
- for reading and writing
- "w+"
- for reading and writing (if file exists then truncate it,
- else create it)
- "a+"
- for reading and writing (if file exists, position at end
- of file, else create it)
In addition, a "b" may be appended to the mode string to indicate
that the file is to be opened in binary mode (the default is text
mode). If a file is opened for reading and writing, only reads or only
writes can be done at any one time. To switch from reading to
writing, or vice versa, an fseek must be performed on the stream,
unless during input an EOF was read.
If you open a file in append mode("a"), your writing is always
appended to the end of the file, even if you call fseek or fgetpos.
- Return Value
-
fopen returns a FILE pointer to an open file. A NULL return value
indicates an error
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fclose
freopen
_open
- Example
/* Example for fopen */
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
if ((fp = fopen("file.dat", "w")) == NULL)
{
perror("Error creating file");
exit(EXIT_FAILURE);
}
printf("Opened file file.dat\n");
fprintf(fp, "This is the first line\n");
printf("Wrote to file\n");
fclose(fp);
printf("Closed file\n");
if ((fp = fopen("file.dat", "a")) == NULL)
{
perror("Error creating file");
exit(EXIT_FAILURE);
}
printf("Opened file file.dat for appending\n");
fprintf(fp, "This is the second line\n");
printf("Added to file\n");
fclose(fp);
printf("Closed file\n");
return 0;
}
- Output
Opened file file.dat
Wrote to file
Closed file
Opened file file.dat for appending
Added to file
Closed file
- Header
- stdio.h
- Prototype
-
int fprintf(FILE *fp, const char *format, arg0... argn);
int printf(const char *format, arg0... argn);
int sprintf(char *buffer, const char *format, ...);
int _snprintf(char *buffer, size_t count, const char *format, ...);
- Description
-
fprintf writes formatted data to the file stream fp.
printf writes formatted data to stdout.
sprintf writes formatted data to buffer and 0 terminates it.
_snprintf function differs from sprintf in that it stores no
more than count characters in buffer.
Arguments are
interpreted according to the null-terminated format string.
The format string is a sequence of characters with embedded
conversion commands. Characters that are not part of the conversion
command are output. Conversion commands consist of:
'%'{flag}[field_width]['.' precision][size_and_dist] conversion_char
where a % always signifies the beginning of a conversion command.
To print a % use %%.
Flag Characters
| -
| Means left justify the conversion
|
| +
| Means that signed conversions always start with a + or -
|
| (Space)
| Means that for positive conversions, the
conversion will start with a space. The + flag
overrides the (Space) flag.
|
| #
| For x or X conversions, if the result is non-zero
then a 0x or 0X will be added to the front of it.
For o conversions, a leading 0 will be added.
|
For floating conversions (e, E, f, g, G),
a decimal point will always appear.
If it is g or G, then trailing 0's will not be truncated.
Field Width
This is a decimal integer controlling the minimum number of
characters printed. If the actual number of characters is less than the
field_width, it is padded with blanks. If the field_width digit
string begins with a 0, it is padded with a 0.
If the field_width is the character *, the actual field_width
value is taken from the next int arg. If the field_width is
negative, it is treated as if the - flag were given and the absolute
value of the field_width is used.
If there are more characters than allowed for by the field_width,
then the width is expanded appropriately.
Precision
Followed by a digit string specifying the precision of the conversion.
If no digits appear after the ., then the precision is taken as 0.
For integral conversions, this is the minimum number of digits.
For g and G, the precision gives the maximum number of digits appearing after
the decimal point.
For s, it is the maximum number of characters in a string.
If precision is the character *, the precision is taken from the
next int argument.
Size and Distance
Size and distance arguments are:
| F
| __far pointer
|
| N
| __near pointer
|
| hh
| char integer
|
| h
| short integer
|
| l
| long integer
|
| ll
| long long integer
|
| j
| intmax_t or uintmax_t integer
|
| z
| size_t integer
|
| t
| ptrdiff_t integer
|
| L
| long double
|
Conversion Character
One of the characters b, d, i, o, u, x, X,
a, A, f, F, e, E, g, G, c,
s, p, n, %.
Other characters cause undefined behavior.
| b, d, i, o, u, x, X
| The argument is an integer and it is converted to a string
of digits according to the conversion character. b is
unsigned binary, o is unsigned octal, u is unsigned
decimal, x and X are unsigned hex, i and d are signed
decimal. For x, lower-case hex letters are used. For X,
upper-case ones are used. If no precision is specified, it
defaults to one. If there are fewer digits than precision,
leading spaces are placed before the digits. If argument
is 0 and precision is 0, no characters are printed.
|
| c
| The least significant byte of the integer argument is
printed as a character.
|
| e, E
| The argument is a double, and is printed in scientifc
notation, [-]d.dddddde+-dd. There is one digit before the
decimal point and precision digits after. The precision
defaults to 6. If the precision is 0, the decimal point is not
written. E is used for the exponent instead of e if the E
conversion character was specified. A minimum of two
digits will appear in the exponent.
|
| f, F
| The argument is a double. It is converted to a decimal
string of the form [-]dd.dddd. The number of digits after
the decimal point is given by the precision, which
defaults to 6. If the precision is 0, no fractional digits or
decimal points appear. The F will result in INF or NAN rather
than inf or nan.
|
| g, G
| The argument is a double. It is printed using f or e (or E
if G was specified) format, depending on the value of the
argument. e will be used if the exponent is less than -3 or greater than the
precision. The precision gives the number of significant
digits; it defaults to 6. The decimal point appears if
followed by a digit; trailing 0's are truncated.
|
| a, A
| The argument is a floating point number, which is converted
to hex in the form [-]0x1.hhhhhp+-d, or 0 if the number is 0.hhhhh
are the digits of the mantissa in hex, and d is the exponent in decimal as
a power of 2. If no precision is specified, sufficient digits will
be generated to produce an exact value. Otherwise, it is rounded to
the specified precision. The A format will render the result in
all upper case. Trailing zeros are omitted. If the # flag is not
specified and the precision is 0, no decimal point is generated.
|
| n
| The argument is a pointer to an int, into which is
written the number of characters printed so far. No
characters are generated or converted by this.
|
| p
| The argument is a pointer that for far pointers is printed
as segment:offset or for near pointers as xxxx.
|
| s
| The argument is a pointer to a string. The characters are
printed until a 0 character is encountered or the number
of characters specified in precision are printed. The
terminating 0 is not printed. The precision defaults to
32767.
|
| %
| The % character is printed.
|
- Return Value
-
The number of characters written or a negative value on error.
For sprintf and _snprintf, the terminating 0 character
is not counted.
For _snprintf, if the number of characters required to store
the data exceeds count, count
characters of data are stored
in buffer and -1 is returned.
- Compatibility
- DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fscanf
vprintf Functions
- Example
/* Example for fprintf */
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *msg = "Integer formats are: ";
int testint = 10;
fprintf(stdout, "%sHex: (%X) Dec: (%d) Oct: (%o) Bin: (%b)\n",
msg, testint, testint, testint, testint);
return 0;
}
- Output
Integer formats are: Hex: (A) Dec: (10) Oct: (12) Bin: (1010)
- Header
-
stdio.h
- Prototype
-
int fputc(int c, FILE *fp);
- Description
- fputc writes the character c to the stream fp.
- Return Value
-
fputc returns the last character output to the stream. An EOF is
returned on error.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
_fputchar
getc
- Header
-
stdio.h
- Prototype
-
int fputs(const char *s, FILE *fp);
- Description
-
fputs writes the string s (excluding the terminating 0) to the stream
fp.
- Return Value
-
Returns non-negative if successful, EOF if a write error occurred.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fgets
gets
puts
- Header
-
stdio.h
- Prototype
-
size_t fread(const void *p, size_t sizelem, size_t n, FILE *fp);
- Description
-
Reads n elements from stream fp into the array that p points to.
sizelem is the number of bytes in each element.
If sizelem or n is zero, fread doesn't change doesn't change the
contents of the array and returns zero.
- Return Value
-
fread returns the number of complete elements actually read. If an
error or an end of file is encountered, it will return less than n.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fwrite
_read
- Example
/* Example for fread */
#include <stdio.h>
#include <stdlib.h>
#define BUFSZ 256
int main()
{
char buf[BUFSZ], fname[_MAX_PATH];
int sizelem, totalnum = BUFSZ, numread;
FILE *fd;
printf("Enter filename: ");
gets (fname);
if ((fd = fopen (fname, "r")) == NULL)
{
perror("Error opening file");
exit (EXIT_FAILURE);
}
sizelem = sizeof (char);
numread = fread (buf, sizelem, totalnum, fd);
printf("Total read %d\n", numread);
printf("Data read\n %.256s", buf);
}
- Output
-
Enter filename: fread.c
Total read 256
Data read
/* Example for fread */
#include <stdio.h>
#include <stdlib.h>
#define BUFSZ 256
int main()
{
char buf[BUFSZ], fname[_MAX_PATH];
int sizelem, totalnum = BUFSZ, numread;
FILE *fd;
printf("Enter filename: ");
gets (fname);
if (
(
fd
- Header
-
stdio.h
- Prototype
-
FILE *freopen(const char *name, const char *mode, FILE *fp);
- Description
-
The freopen function closes the file indicated by fp. Errors while
closing the file are ignored. The function then opens a new file and
associates the stream fp with it. name and mode have the same
meaning as in fopen.
- Return Value
-
freopen returns fp if successful, otherwise a NULL.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fclose
fopen
_open
- Example
/* Example for freopen */
#include <stdlib.h>
#include <stdio.h>
int main()
{
FILE *fp;
char fname1[_MAX_PATH], fname2[_MAX_PATH];
printf("Enter the first filename: ");
gets (fname1);
printf("Enter the second filename: ");
gets (fname2);
if ((fp = fopen (fname1, "r")) == NULL)
{
perror("Could not open first file");
exit (EXIT_FAILURE);
}
printf("File \"%s\" is now open\n", fname1);
if ((fp = freopen (fname2, "r", fp)) == NULL)
{
perror("Could not reopen to second file");
exit (EXIT_FAILURE);
}
printf("File \"%s\" closed and \"%s\" is now
open\n", fname1, fname2);
}
- Output
Enter the first filename: fread.c
Enter the second filename: freopen.c
File "fread.c" is now open
File "fread.c" closed and "freopen.c" is now open
- Header
- stdio.h
- Prototype
-
int fscanf(FILE *fp, const char *format, ...);
int scanf(char *format, ...);
int sscanf(const char *buffer, const char *format, ...);
- Description
-
fscanf reads characters from the input stream fp.
scanf reads characters from the input stream stdin.
sscanf reads characters from the string buffer.
Characters read are
converted according to the format string and the values created are
stored through the argument pointers. Note that the arguments are
pointers to where values will be stored.
The format string consists of:
The conversion specification specifies how input characters are to be
converted and assigned through the corresponding argument
pointers. Conversion continues until a conflicting input character is
encountered or the field_width is reached. * is an assignment
suppression flag. It causes the conversion to be performed but the
result is ignored. There is no corresponding argument pointer for
this. If there are less argument pointers than conversion specification
the results are unpredictable. If there are extra argument pointers the
excess ones are ignored.
Field Width
field_width is a sequence of decimal digits specifying the
maximum number of characters in the field.
Size
| hh
| The following b,d,i,o,u,x,X or n refers to an argument that
is a pointer to a char.
|
| h
| Argument is a pointer to a short.
|
| l
| A following b,d,i,o,u,x,X or n refers to an argument that
is a pointer to a long. A following a,A,e,E,f,F,g,G refers
to an argument that is a pointer to a double. A following c, s
or [ refers to an argument that is a pointer to a wchar_t.
|
| ll
| A following b,d,i,o,u,x,X or n refers to an argument that
is a pointer to a long long.
|
| j
| A following b,d,i,o,u,x,X or n refers to an argument that
is a pointer to a intmax_t.
|
| z
| A following b,d,i,o,u,x,X or n refers to an argument that
is a pointer to a size_t.
|
| t
| A following b,d,i,o,u,x,X or n refers to an argument that
is a pointer to a ptrdiff_t.
|
| L
| A following a,A,e,E,f,F,g,G refers
to an argument that is a pointer to a long double.
|
Distance
The distance characters for the next argument are:
| N
| Near pointer
|
| F
| Far pointer
|
Conversion Character
The conversion characters are:
| b
| A binary number is expected, the argument pointer must
be a pointer to an int.
|
| d
| An integer is expected, the argument pointer must be a
pointer to an int.
|
| a, e, f, g
| A floating-point number is expected. Argument pointer
must be a pointer to a float (double if l or L is used).
|
| i
| An integer is expected. If it starts with a 0, it is taken to be
octal. If it starts with 0x or 0X, it is hexadecimal. The
argument pointer must be a pointer to an int.
|
| o
| An octal number is expected. The argument pointer must
be a pointer to an int.
|
| p
| A hexadecimal integer is expected. The argument pointer
must be a pointer to a pointer.
|
| u
| An unsigned int is expected, the argument pointer
must be a pointer to an unsigned.
|
| n
| An int value is stored through the corresponding
argument pointer, specifying the number of characters
read up to this point by this call to fscanf.
|
| [
| A string is expected. Between the [and a closing ] are
characters acceptable to the string. If the [is immediately
followed by a ^, acceptable characters for the string are all
those except the ones between the ^ and the ] . The
argument pointer must be a pointer to a character array. A
NULL character is appended to the string.
|
| s
| A string is expected. The argument pointer must be a
pointer to a string. The input field extends until a space or
newline is read, which is not part of the field. A NULL
character is appended to the string.
|
| c
| A character is expected. The argument pointer must be a
pointer to a character. If a field_width is specified,
then that many characters are read and the argument
pointer must point to a character array large enough to
hold the result.
|
| %
| Match the input with a %.
|
The conversion characters a, e, f, g, and x may be uppercase, with no
difference in meaning. Other conversion characters will cause
unexpected results. Conflicting characters are left unread in the input
stream. There is no direct way to determine if suppressed
assignments or literal matches succeeded, unless %n is used.
- Return Value
-
The number of assigned input items excluding any assignment
suppressed conversions. If end of file is encountered before
assignments are done or before conflicts occur, EOF is returned.
fscanf returns when it reaches the end of the format string.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fprintf
- Example
-
/* Example for fscanf */
#include <stdio.h>
#include <stdlib.h>
int main()
{
char first[16], last[16];
int age;
int res;
printf("Enter your first and last name in
the form \" first last\": ");
res = fscanf(stdin, "%s %s", first, last);
if (res != 2)
{
printf("Error reading name.\n");
exit (EXIT_FAILURE);
}
printf("Your name is %s %s.\n", first, last);
printf("How old are you %s? ", first);
res = fscanf(stdin, "%d", &age);
if (res != 1)
{
printf("Error reading age.\n");
exit(EXIT_FAILURE);
}
printf("Oh, %d.\n", age);
return 0;
}
- Output
Enter your first and last name in the form
"first last": John Doe
Your name is John Doe.
How old are you John? 32
Oh, 32.
- Example 2
-
/* Example of sscanf */
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *buf = "1.24...";
char str[8];
float f;
int i;
sscanf(buf, "%s", str);
sscanf(buf, "%f", &f);
sscanf(buf, "%d", &i);
printf("Scanned \"%s\" for a string, float and integer\n", buf);
printf("String: \"%s\"\n", str);
printf("Float: %f\n", f);
printf("Integer: %d\n", i);
return 0;
}
- Output
Scanned "1.24..." for a string, a float and an integer
String: "1.24..."
Float: 1.240000
Integer: 1
- Header
-
stdio.h
- Prototype
-
int fseek(FILE *fp, long offset, int origin);
- Description
-
Sets the file position associated with the stream fp.
offset is the
signed offset in bytes relative to that specified by origin.
Values for
origin are defined in io.h and stdio.h:
| origin
| Description
|
| SEEK_SET
| Beginning of file
|
| SEEK_CUR
| Current position
|
| SEEK_END
| End of file
|
If the file is opened in text mode, offset can be only a value
returned by ftell and origin can be only SEEK_SET, or offset
must be 0. If an ungetc was called immediately before fseek,
ungetc is undone. If the file was opened in read/write mode (see
fopen) following fseek, reading or writing may be performed.
- Return Value
-
fseek returns 0 if the pointer was successfully moved. fseek
returns a non-zero value if an error occurs.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
ftell
_lseek
- Example
/* Example of fseek */
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
long offset, lpos;
char c;
fp = fopen("\\dm\\include\\io.h", "r");
if (fp < 0)
perror("Error opening file");
else
{
offset = 35L;
if (fseek (fp, offset, SEEK_SET) != 0)
{
perror("Error seeking");
exit (EXIT_FAILURE);
}
c = fgetc(fp);
printf("Character at position 35 is %d\n", c);
offset = 10L;
if (fseek (fp, offset, SEEK_CUR) != 0)
{
perror("Error seeking");
exit (EXIT_FAILURE);
}
c = fgetc(fp);
printf("Character at prior position + 10 is %d\n", c);
offset = 0L;
if (fseek (fp, offset, SEEK_END) != 0)
{
perror("Error seeking");
exit (EXIT_FAILURE);
}
c = fgetc(fp);
printf("Character at end of file is %d\n", c);
fclose(fp);
}
}
- Output
Character at position 35 is 116
Character at prior position + 10 is 105
Character at end of file is -1
- Header
-
stdio.h
- Prototype
-
int fsetpos(FILE *fp, const fpos_t *pos);
- Description
-
The function fsetpos restores the position of the stream fp as
previously saved in pos by a call to fgetpos.
- Return Value
-
0 if successful, otherwise non-zero with errno set.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fgetpos
- Example
-
See fgetpos
- Header
-
stdio.h
- Prototype
-
long ftell(FILE *fp);
- Description
-
ftell returns the current position in the file associated with the
stream fp. If the file is opened in text mode, the returned value may
not accurately reflect the number of bytes actually read or written.
- Return Value
-
ftell returns the current file position. If an error occurs -1 is
returned and errno is set.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fseek
_isatty
- Example
/* Example for ftell */
#include <stdlib.h>
#include <stdio.h>
#include <io.h>
#include <string.h>
int main()
{
char fname[_MAX_PATH];
char line[128];
FILE *fp;
long offset;
printf("Enter a filename: ");
gets (fname);
if ((fp = fopen(fname, "r")) == NULL)
{
perror("Unable to open input file");
exit (EXIT_FAILURE);
}
setbuf(fp, NULL);
fgets(line, 128, fp);
if (line[strlen (line) -1] == '\n')
line[strlen (line) -1] = '\x00';
offset = ftell(fp);
printf("After reading the first line in file
\"%s\":\n \"%s\"\n", fname, line);
printf("The file pointer is at offset:
%d\n", offset);
fclose(fp);
}
- Output
Enter a filename: ftell.c
After reading the first line in file "ftell.c":
"/*"
The file pointer is at offset: 4
- Prototype
-
size_t fwrite(const void *buffer, size_t sizelem,
size_t n, FILE *fp);
- Description
-
The function fwrite writes n elements of sizelem bytes from
buffer to the stream fp.
- Return Value
-
Returns the number of complete elements actually written, which
may be less than n if an error occurred.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fread
- Example
-
/* Example for fwrite */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp;
char *str = "Write this data to file";
char buffer[128];
int count, nwritten, nread;
count = strlen (str) + 1;
fp = fopen("file.dat", "w+");
if (fp == NULL)
{
perror("Unable to create file: file.dat");
exit (EXIT_FAILURE);
}
printf("Writing string \"%s\" to file...\n",
str);
nwritten = fwrite(str, sizeof(char), count, fp);
printf("%d bytes written\n", nwritten);
rewind(fp);
printf("Reading back from file...\n");
nread = fread(buffer, sizeof(char), count, fp);
printf("%d bytes read from file\nString read
is \"%s\"\n", nread, buffer);
fclose(fp);
return 0;
}
- Output
Writing string "Write this data to file" to
file...
24 bytes written
Reading back from file...
24 bytes read from file
String read is "Write this data to file"
- Header
-
stdio.h
- Prototype
-
int getc(FILE *fp);
- Description
-
getc obtains one character from the stream fp. Input is line-buffered
and therefore a carriage return is required before the
character is returned.
- Return Value
-
Returns the next character of the line read. Otherwise, returns a
value of EOF on error.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fgetc
_getch
getchar
_getche
putc
ungetc
- Example
/* Example for getc */
#include <stdio.h>
#include <stdlib.h>
int main()
{
int input;
printf("Input a character then hit return: ");
input = getc(stdin);
printf("'%c' was returned by getc()\n", input);
}
- Output
Input a character then hit return: g 'g' was returned by getc()
- Header
-
stdio.h
- Prototype
-
int getchar(void);
- Description
-
The getchar function gets a character from the stream stdin.
- Return Value
-
Returns the next character read. On error returns a value of EOF.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fgetc
getc
getchar
_getche
putchar
_getch
ungetc
- Example
/* Example for getchar */
#include <stdio.h>
#include <stdlib.h>
int main()
{
int input;
printf("Input a character then press
return: ");
input = getchar();
printf("'%c' was returned by getchar()\n",
input);
}
- Output
Input a character then press return: g 'g' was returned by getchar()
- Header
-
stdio.h
- Prototype
-
char *gets(char *str);
- Description
-
Read characters from stdin into the string str until a newline is
read or an end-of-file is encountered. Newlines are not written to the
string. The string is terminated with a NULL character. str must be
large enough to hold the resulting string.
- Return Value
-
Returns str if successful. A NULL is returned if an end-of-file is
encountered and no characters have been written to str, or if a
read error occurs.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fgets
puts
- Example
/* Example for gets
Also demonstrates puts
gets.c
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
char buffer[128];
printf("Type something: ");
gets (buffer);
printf("You typed: ");
puts (buffer);
}
- Output
c:\dm\examples> gets
Type something: Hello there
You typed: Hello there
- Header
-
stdio.h
- Prototype
-
int putc(int c, FILE *fp);
- Description
-
The putc function writes the character c to the stream fp.
- Return Value
-
Returns the character just written. EOF is returned if an error occurs.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fputc
getc
putchar
- Example
/* Example for putc */
#include <stdio.h>
#include &stdlib.h>
int main()
{
char *string = "This is an example of putc()";
char *scan = string;
while (* scan)
{
if (putc(* scan, stdout) == EOF)
exit(EXIT_FAILURE);
scan++;
}
}
- Output
This is an example of putc()
- Header
-
stdio.h
- Prototype
-
int putchar(int c);
- Description
-
The putchar function writes the character c to the standard output
stream, stdout (usually the screen).
- Return Value
-
Returns the character just written. EOF is returned if an error occurs.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fputc
getchar
putc
- Example
/* Example for putchar */
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *string = "This is an example of putchar()";
char *scan = string;
while (* scan)
{
if (putchar(* scan) == EOF)
exit(EXIT_FAILURE);
scan++;
}
}
- Output
This is an example of putchar()
- Header
-
stdio.h
- Prototype
-
int puts(const char *s);
- Description
-
The puts function writes the string s to stdout (without the
terminating 0), and then writes a newline to stdout.
- Return Value
-
Returns a positive value if successful, otherwise EOF.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fprintf
fputs
gets
- Example
/* Example for puts */
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *str1 = "Display this string using puts().";
char *str2 = "Notice that puts() adds a
newline to the end.";
puts (str1);
puts (str2);
}
- Output
Display this string using puts().
Notice that puts() adds a newline to the end.
- Prototype
-
void rewind(FILE *fp);
- Description
- rewind repositions the file pointer associated with a stream to the
beginning of the file. This is equivalent to using
fseek(fp, 0L, SEEK_SET), with the error flag for fp being
cleared.
- Return Value
-
None
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fseek
- Example
/* Example for rewind */
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char *str1 = "String one, example string.";
char *str2 = "xxxxxxxxxxxxx";
char buffer[80];
fp = fopen("file.dat", "w+");
fprintf(fp, "%s", str1);
rewind(fp);
fprintf(fp, "%s", str2);
rewind(fp);
fgets(buffer, 80, fp);
printf("The value read back is: \"%s\"\n", buffer);
return 0;
}
- Output
The value read back is: "xxxxxxxxxxxxxxample string."
- Header
-
stdio.h
- Prototype
-
void setbuf(FILE *stream, char *buffer);
- Description
- The setbuf function sets the buffering system for bytes read or
written to a stream. If the buffer argument is NULL, the stream is
unbuffered. If buffer is not NULL, it is taken to be a pointer to the
buffer which is to be used for subsequent read and write calls.
buffer must point to a character array of size BUFSIZ (defined in
stdio.h). The user specified buffer is used then instead of the
default system-allocated I/ O buffer.
- Return Value
-
None
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
setvbuf
- Example
/* Example for setbuf */
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char buffer[BUFSIZ];
fp = fopen("file.dat", "w+");
setbuf (fp, buffer);
printf("Stream has been set to buffer at
%Fp\n", buffer);
setbuf (fp, NULL);
printf("Now stream buffering has been
turned off\n");
}
- Output
Stream has been set to buffer at 0334: 15F0
Now stream buffering has been turned off
- Header
-
stdio.h
- Prototype
-
int setvbuf(FILE *fp, char *buf, int mode, size_t size);
- Description
- setvbuf specifies the type and size of a buffer used for a stream. In
addition to the function parameters the following global variable
affects the behaviour of this function: _okbigbuf, which is used
only in the T, S, and M memory models under MS-DOS. _okbigbuf
controls how buffers are allocated when buf is NULL. It is statically
initialized to 0 or 1 by the programmer (the library sets it to 1 by
default). If _okbigbuf is 1 and the memory model is T, S, or M:
setvbuf tries to allocate a buffer outside of the data segment. If
that fails, and size <= BUFSIZ, then setvbuf tries to allocate a
buffer within the data segment. A buffer that is outside the data
segment is marked by setting _IOBIGBUF in fp->_flags. If
_okbigbuf is 0 or the memory model is C or L: setvbuf tries to
allocate a buffer within the data segment. A buffer allocated by
setvbuf is flagged by _IOMYBUF being set in fp->_flags.
The function parameters are:
Argument/Description
- fp
- Stream pointer that is already opened, but before any reads or writes have been done to the stream.
- buf
- Pointer to buffer, or NULL. If NULL, then setvbuf uses malloc or faralloc to allocate a buffer of size bytes. If buf is not NULL, it points to a buffer that setvbuf causes to be associated with the stream fp.
- mode
- Buffering mode. Use a value from the next table.
- size
- If buf is NULL, size is the number of bytes to allocate for the buffer. If buf is not NULL, size must be the number of bytes in the buffer that buf points to.
mode can be one of these values:
Constant/Description
- _IONBF
- No buffering. buf and size are ignored. Unbuffered I/ O means data written is immediately passed to DOS. When data is read, exactly enough is read.
- _IOLBF
- Do line buffering. The actual I/ O is performed when a newline is read or written.
- _IOFBF
- Full buffering. Data are read a full buffer at a time and are written only when the buffer is full.
- Return Value
-
If the call succeeds, the various fields that fp points to are updated
to show the buffer and 0 is returned. If memory is insufficient for the
buffer or if the mode parameter is invalid, non-zero is returned.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
setbuf
- Example
/* Example of setvbuf */
#include <stdio.h>
#include <stdlib.h>
#define OURBUFSIZE 1024
int main()
{
FILE *fp;
char buffer[OURBUFSIZE];
fp = fopen("file.dat", "w+");
setvbuf (fp, buffer, _IOFBF, OURBUFSIZE);
printf("Stream buffering has been set to
%d bytes at %Fp\n", OURBUFSIZE,
buffer);
setvbuf (fp, NULL, _IONBF, 0);
printf("Now stream buffering has been
turned off\n");
}
- Output
Stream buffering has been set to 1024 bytes at
0340: 1400
Now stream buffering has been turned off
- Header
-
stdio.h
- Prototype
- extern FILE *stderr;
- Description
- stderr is a constant FILE pointer to the standard error stream, which is usually the console display. To print error messages that users must see, stderr is preferred over stdout. Due to file redirection, errors printed to stdout can end up in files, whereas stderr cannot be redirected.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
_stdaux
stdin
stdout
_stdprn
- Header
-
stdio.h
- Prototype
- extern FILE *stdin;
- Description
- stdin is a constant FILE pointer to the standard input stream, which is usually the keyboard or a redirected file. When the user redirects a file using the input redirection operator (<) or the pipe operator(|), the redirected data will arrive on the stdin stream. Filter programs, such as the DOS programs MORE and SORT, use stdin.
Some functions use the stdin stream by default. Examples are getchar and scanf functions. getchar() is the same as getc(stdin), only shorter.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
_stdaux
stderr
stdout
_stdprn
- Header
-
stdio.h
- Prototype
- extern FILE *stdout;
- Description
- stdout is a constant FILE pointer to the standard output stream, which is usually the console display or a redirected file. When a user redirects a file using the output redirection operator (>) or the pipe operator (|), the redirected data will go out to the stdout stream. Filter programs, such as DOS programs MORE and SORT, use stdout.
Some functions use the stdout stream by default. Examples are the putchar and printf. Function putchar('a') is the same as putc(stdout, 'a'), only shorter.
stdout and the other standard streams do not need to be opened or closed. They are set to their standard devices or redirected to files by the operating system before a program begins. All files are closed when a program termines.
A program that spawns a child process can use freopen to set the standard file pointers for the child process.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
_stdaux
stderr
stdin
_stdprn
- Header
-
stdio.h
- Prototype
-
FILE *tmpfile(void);
- Description
-
The tmpfile function creates a temporary file and returns a pointer
to the stream associated with the file. The file is automatically
deleted when it is closed or when the program terminates normally,
as long as the current working directory does not change. The
temporary file is opened in binary read/ write mode.
- Return Value
-
Returns a stream pointer. If unsuccessful, a NULL pointer is returned.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
_rmtmp
_tempnam
tmpnam
- Example
/* Example for tmpfile */
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp; char *str = "The quick brown dog jumped over
the lazy cat";
char buf[128];
if ((fp = tmpfile ()) == NULL)
{
perror("Could not open temporary file");
exit (EXIT_FAILURE);
}
printf("Created temporary file\n");
printf("Writing to file: \"%s\"\n", str);
fputs (str, fp);
rewind(fp);
fgets (buf, 128, fp);
printf("Read from file: \"%s\"\n", buf);
fclose(fp);
}
- Output
Created temporary file
Writing to file: "The quick brown dog jumped
over the lazy cat"
Read from file: "The quick brown dog jumped over
the lazy cat"
- Header
-
stdio.h
- Prototype
-
char *tmpnam(const char *s);
- Description
-
The tmpnam function generates a unique temporary filename that is
valid, but not the same as, the name of any existing file. tmpnam
generates a different string each time it is called, with a maximum
defined by the macro TMP_MAX, found in stdio.h. The argument
passed to tmpnam can be either a pointer to a buffer, which should
be L_tmpnam characters, or a NULL pointer. The path of the file
name will be P_tmpdir.
- Return Value
-
If the argument passed to tmpnam is a pointer to a buffer, the
temporary filename is placed in this buffer, and the return value is a
pointer to this buffer. If the argument to tmpnam is a NULL pointer,
the file name is placed in a static data area, overwritten at each call
to tmpnam, and a pointer to this static data buffer is returned.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
_tempnam
- Example
/* Example for tmpnam */
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *name;
if ((name = tmpnam (NULL)) == NULL)
{
perror("Unable to create temporary
filename");
exit (EXIT_FAILURE);
}
printf("Temporary filename \"%s\"
created.\n", name);
free (name);
}
- Header
-
stdio.h
- Prototype
-
int ungetc(int c, FILE *fp);
- Description
-
Puts character c back into the input stream fp, where it is read by
the next input operation on the stream. If an fseek, fsetpos, or
rewind is done between an ungetc and the next read, the
character is lost. Only one character may be put back between reads.
EOF cannot be placed back. If ungetc is called at the end of a file,
ungetc clears the EOF indicator.
- Return Value
-
c if successful; otherwise EOF if the character cannot be pushed
back.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
getc
_ungetch
- Example
/* Example for ungetc */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define delim "\n\r\t\v "
int isdelim(int c)
{
return (strchr(delim, c) != NULL);
}
char *gettoken(FILE *fp)
{
static char tokbuf[128];
int c;
int pos = 0;
c = fgetc(fp);
if (c == EOF)
{
if (!feof(fp))
perror("error reading from file");
return NULL;
}
if (isdelim(c))
do
{
c = fgetc(fp);
} while ((isdelim (c)) && (c != EOF));
if (c != EOF)
do
{
tokbuf[pos] = c;
pos++;
c = fgetc(fp);
} while ((!isdelim(c)) && (c != EOF));
ungetc(c, fp);
tokbuf[pos] = '\x00';
return tokbuf;
}
int main()
{
char fname[_MAX_PATH];
char *token;
FILE *fp;
printf("Enter filename: ");
gets(fname);
if ((fp = fopen(fname, "r")) == NULL)
{
perror("Unable to open file");
exit(EXIT_FAILURE);
}
do
{
token = gettoken(fp);
printf("%s\n", token);
} while (!feof(fp));
}
- Output
Enter filename: ungetc.c
/* Example for
ungetc
*/
#include
<stdio.h>
#include
<stdlib.h>
.
.
.
=
gettoken
(fp);
printf
("%s\n",
token);
}
while (! feof(fp));
}
- Header
-
stdio.h
stdarg.h
varargs.h
- Prototype
-
int vfprintf(FILE *stream, const char *format, va_list arg_ptr);
int vprintf(const char *format, va_list arg_ptr);
int _vsnprintf(char *buffer, size_t count, const char *format, va_list arg_ptr);
int vsprintf(char *buffer, const char *format, va_list arg_ptr);
- Description
-
These functions format and send data to the appropriate place.
vfprintf sends data to the file specified by stream;
vprintf sends data to standard output;
vsprintf and _vsnprintf send
data to the memory pointed to by buffer.
The _vsnprintf
function differs from vsprintf in that it writes not more than
count bytes to buffer.
These functions are similar to printf, fprintf and sprintf
except the data are taken from the arg_ptr.
- Return Value
-
The number of characters written, not counting the terminating null
character. If an error occurs, a negative value is returned. For
_vsnprintf, if the number of bytes to write exceeds count, then
count bytes are written and -1 is returned.
- Compatibility
-
DOS Windows 3.x Phar Lap DOSX Win32
- See Also
-
fprintf
- Example
/* Example for vfprintf
Also demonstrates vprintf, _vsnprintf,
vsprintf
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
void echo_err_printf(char *format, ...)
{
va_list arg_ptr;
va_start(arg_ptr, format);
vfprintf(stderr, format, arg_ptr);
va_end(arg_ptr);
va_start(arg_ptr, format);
vprintf(format, arg_ptr);
va_end(arg_ptr);
}
int main()
{
echo_err_printf("Error: %d\n", 12);
}
- Output
Error: 12
Error: 12
|