Last update Sep 15, 2002
/* 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); } }
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. |
/* 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); } } }
The first line of temp.dat is:This is an 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); }
The character read from stdin is : j
/* 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)); }
The handle for stdin is 0 The handle for stdout is 1 The handle for stderr is 2
/* Example for _flushall */ #include <stdio.h> #include <stdlib.h> int main() { int tf; tf = _flushall (); printf("%d streams flushed\n", tf); }
/* 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)); }
/* 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); }
/* Example for _getw Also demonstrates _putw, fopen, fclose, rand */ #include#include 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); }
Read 16838 5758 10113 17515 31051 5627 23010
7419 16212 4086
° 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.
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.
/* 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); }
/* 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); }
/* 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); } }
/* 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"); } }
See Also
/* 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"); }
/* 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"); }
/* 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); }
/* 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"); }
Enter data terminated by ctrl-z: Hello from Digital Mars Hello from Digital Mars ^Z
/* 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); }
/* 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); }
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.
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.
/* 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"); }
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
- | 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 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:
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. |
/* 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; }
Integer formats are: Hex: (A) Dec: (10) Oct: (12) Bin: (1010)
If sizelem or n is zero, fread doesn't change doesn't change the contents of the array and returns zero.
/* 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); }
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
/* 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); }
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
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.
/* 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; }
/* 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; }
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.
/* 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); } }
/* 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); }
/* 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); }
/* 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); }
/* 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); }
/* 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); }
c:\dm\examples> gets Type something: Hello there You typed: Hello there
/* 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++; } }
/* 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++; } }
/* 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); }
/* 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); }
/* 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"); }
The function parameters are:
mode can be one of these values:
/* 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"); }
Some functions use the stdin stream by default. Examples are getchar and scanf functions. getchar() is the same as getc(stdin), only shorter.
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.
/* Example for tmpfile */ #include#include 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); }
/* 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); }
/* 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)); }
Enter filename: ungetc.c /* Example for ungetc */ #include <stdio.h> #include <stdlib.h> . . . = gettoken (fp); printf ("%s\n", token); } while (! feof(fp)); }
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);
These functions are similar to printf, fprintf and sprintf except the data are taken from the arg_ptr.
/* 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); }