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
Example
/* Example for _fcloseall Also demonstrates fopen */ #include <stdio.h> #include <stdlib.h> void 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); } }
Output
Fcloseall closed 2 streams
stdio.h (for _fdopen)
Prototype
FILE *_fdopen(int fd, const char *mode);
Description
The _fdopen function 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 the first argument and the file mode as the second. 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 the mode argument are:
Value/Meaning
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
Example
/* Example for _fdopen Also demonstrates open, fgets */ #include <dos.h*gt #include <fcntl. h> #include <io. h> #include <stdio.h> #include <stdlib.h> void 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.
stdio.h
Prototype
int _fgetchar(void);
Description
The _fgetchar function 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, EOF is returned.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
Example
/* Example for _fgetchar */ #include <stdio.h> #include <stdlib.h> void 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
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
Example
/* Example for _fileno */ #include <stdio.h> #include <stdlib.h> void 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
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
Example
/* Example for _flushall */ #include <stdio.h> #include <stdlib.h> void main () { int tf; tf = _flushall (); printf ("%d streams flushed\n", tf); }Output
5 streams flushed
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
Example
/* Example for fputchar */ #include <stdio.h> void 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
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:
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> void 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.
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
Example
/* Example for _getw Also demonstrates _putw, fopen, fclose, rand */ #includeOutput#include void 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); }
Writing 16838 5758 10113 17515 31051 5627 23010
7419 16212 4086
Read 16838 5758 10113 17515 31051 5627 23010
7419 16212 4086
tsr.h
Declaration
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
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
Example
See getw
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
Example
/* Example of _rmtmp */ #include <stdio.h> #include <stdlib.h> void 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
stdio.h
Prototype
int _snprintf(char *buffer, size_t count, const char *format, ...);
Description
The _snprintf function is a formatted print routine that stores no more than count characters in buffer. Arguments (if any are provided after the format argument) are interpreted according to the zero-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. For a full list of the conversion commands, refer to the entry for fprintf.
The _snprintf function differs from sprintf in that it stores no more than count characters in buffer.
Return Value
Return the number of characters written, not counting the terminating NULL character. If an error occurred, a negative value is returned. If the number of bytes required to store the data exceeds count, count bytes of data are stored in buffer and -1 is returned.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
sprintf
fprintf
printf
vprintf Functions
Example
See fprintf
stdio.h
Declaration
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
stdio.h
Declaration
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
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
Example
/* Example for _tempnam */ #include <stdio.h> #include <stdlib.h> void 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.
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
Example
/* Example for clearerr */ #include <stdio.h> #include <stdlib.h> void 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
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
Example
/* Example for fclose Also demonstrates fopen */ #include <stdio.h> #include <stdlib.h> void 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
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
Example
/* Example for feof Also demonstrates fopen, fgets */ #include <stdio.h> #include <stdlib.h> #define BUFSIZE 128 char buffer[BUFSIZE]; void 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.
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
Example
/* Example for ferror Also demonstrates clearerr */ #include <stdio.h> #include <stdlib.h> void 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
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
Example
/* Example for fflush */ #include <stdio.h> #include <stdlib.h> void 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.
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> void 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
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
Example
/* Example for fgetpos, fsetpos Also demonstrates */ #include <stdio.h> #include <stdlib.h> void 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.
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
Example
/* Example for fgets Also demonstrates */ #include <stdio.h> #include <stdlib.h> void 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.
stdio.h
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:
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
Example
/* Example for fopen */ #include <stdio.h> #include <stdlib.h> void 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"); }Output
Opened file file.dat
Wrote to file
Closed file
Opened file file.dat for appending
Added to file
Closed file
stdio.h
Prototype
int fprintf(FILE *fp, const char *format, arg0... argn);
Description
fprintf writes formatted data to the file stream fp. 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_charwhere a % always signifies the beginning of a conversion command. To print a % use %%.
Flag Characters
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 the precision starts with a 0, then the conversion is 0 padded. If precision is the character *, the precision is taken from the next int argument.
Size and Distance
Size and distance arguments are:
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.
Return Value
The number of characters written or a negative value on error.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
printf
scanf
sprintf
vprintf Functions
Example
/* Example for fprintf */ #include <stdio.h> #include <stdlib.h> void 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); }Output
Integer formats are: Hex: (A) Dec: (10) Oct: (12) Bin: (1010)
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
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
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
Example
/* Example for fread */ #include <stdio.h> #include <stdlib.h> #define BUFSZ 256 void 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 void main () { char buf[BUFSZ], fname[_MAX_PATH]; int sizelem, totalnum = BUFSZ, numread; FILE *fd; printf ("Enter filename: "); gets (fname); if ((fd
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
Example
/* Example for freopen */ #include <stdlib.h> #include <stdio.h> void 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
stdio.h
Prototype
int fscanf(FILE *fp, const char *format, arg0... argn);
Description
Reads characters from the input stream fp. 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:
'%' ['*'] [field-width] [size] [dist] conv_char
Field Width
The field width is a sequence of decimal digits specifying the maximum number of characters in the field.
Size
The distance characters for the next argument are:
The conversion characters are:
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
Example
/* Example for fscanf */ #include <stdio.h> #include <stdlib.h> void 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); }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.
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:
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
Example
/* Example of fseek */ #include <io. h> #include <stdio.h> #include <stdlib.h> void main () { FILE *fp; long offset, lpos; char c; fp = fopen ("\\sc\\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
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
Example
See fgetpos
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
Example
/* Example for ftell */ #include <stdlib.h> #include <stdio.h> #include <io. h> #include <string.h> void 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
stdio.h
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
Example
/* Example for fwrite */ #include <stdlib.h> #include <stdio.h> #include <string.h> void 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); }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"
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> void 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()
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> void 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()
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
Example
/* Example for gets Also demonstrates puts GETS. C */ #include <stdio.h> #include <stdlib.h> void main () { char buffer[128]; printf ("Type something: "); gets (buffer); printf ("You typed: "); puts (buffer); }Output
C:\SC\EXAMPLES> gets Type something: Hello there You typed: Hello there
stdio.h
Prototype
int printf(const char *format, arg0... argn);
Description
The printf function is the formatted print routine; it writes its characters to stdout. Arguments are interpreted according to the zero-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. For a full list of the conversion commands refer to the entry for fprintf.
Return Value
Returns the number of characters written. If an output error occurred, a negative integer is returned.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
fprintf
scanf
sprintf
vprintf Functions
Example
See fprintf
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
Example
/* Example for putc */ #include <stdio.h> #include &stdlib.h> void 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()
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
Example
/* Example for putchar */ #include <stdio.h> #include <stdlib.h> void 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()
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
Example
/* Example for puts */ #include <stdio.h> #include <stdlib.h> void 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.
stdio.h
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
Example
/* Example for rewind */ #include <stdio.h> #include <stdlib.h> void 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); }Output
The value read back is: "xxxxxxxxxxxxxxample string."
stdio.h
Prototype
int scanf(char *format, arg0... argn);
Description
scanf is a formatted input routine which obtains its input from stdin. Apart from the format string, the arguments must be pointers to where values are stored. For details of the format and usage of this function refer to the entry for fscanf.
Return Value
The number of assigned input items excluding any assignment suppressed conversions is returned. If the end of the string is encountered before any assignments are done or before any conflicts occur, an EOF is returned. scanf normally returns when it reaches the end of the format string.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
Example
/* Example for scanf */ #include <stdio.h> #include <stdlib.h> void main () { unsigned int val; printf ("Enter a decimal value: "); scanf ("%i", &val); printf ("The decimal number %d, is %04x in hexadecimal\n", val, val); }Output
Enter a decimal value: 63
The decimal number 63, is 003f in hexadecimal
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
Example
/* Example for setbuf */ #include <stdio.h> #include <stdlib.h> void 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
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:
mode can be one of these values:
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
Example
/* Example of setvbuf */ #include <stdio.h> #include <stdlib.h> #define OURBUFSIZE 1024 void 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
stdio.h
Prototype
int sprintf(char *buffer, const char *format,...);
Description
sprintf is a formatted print routine that writes its characters to the memory buffer specified by buffer. Arguments (if any are provided after the format argument) are interpreted according to the zero-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. For a full list of the conversion commands, refer to the entry for fprintf.
The _snprintf function differs from sprintf in that it stores no more than count characters in buffer.
Return Value
Returns the number of characters written, not counting the terminating NULL character. Returns a negative value if an error occurrs.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_snprintf
fprintf
printf
scanf
vprintf Functions
Example
See fprintf
stdio.h
Prototype
int sscanf(const char *buffer, const char *format,...);
Description
The sscanf function reads from the specified buffer using the specified format. The additional arguments must be pointers to where the values are to be stored. For details of the format and usage refer to the entry for fscanf.
Return Value
The number of assigned input items excluding any assignment suppressed conversions is returned. If the end of the string is encountered before any assignments are done or before any conflicts occur, an EOF is returned. sscanf normally returns when it reaches the end of the format string.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
Example
/* Example of sscanf */ #include <stdio.h> #include <stdlib.h> void 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, a float and an integer\n", buf); printf ("String: \"%s\"\n", str); printf ("Float: %f\n", f); printf ("Integer: %d\n", i); }
Output
Scanned "1.24..." for a string, a float and an integer
String: "1.24..."
Float: 1.240000
Integer: 1
stdio.h
Declaration
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
stdio.h
Declaration
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
stdio.h
Declaration
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
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
Example
/* Example for tmpfile */ #includeOutput#include void 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); }
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"
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
Example
/* Example for tmpnam */ #include <stdio.h> #include <stdlib.h> void 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); }
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 you use ungetc 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
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; } void 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)); }
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 va_list 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 buffer, then count bytes are written and -1 is returned.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
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); } void main () { echo_err_printf ("Error: %d\n", 12); }Output
Error: 12
Error: 12