16.05.2015 Views

Working with the Unix OS

Working with the Unix OS

Working with the Unix OS

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

C Libraries<br />

6. C LIBRARIES<br />

Input and Output<br />

I/O streams that point to a file are block buffered.<br />

Streams that point to a terminal (stdin & stdout) are line buffered.<br />

To explicitly direct <strong>the</strong> system to flush <strong>the</strong> buffer at any time use <strong>the</strong> function 'ff lush"<br />

void setbuf(FILE *stream, char *buf)<br />

If you pass a null pointer as <strong>the</strong> buffer, <strong>the</strong> stream is unbuffered.<br />

header file – standard I/0 functions<br />

- prototype declarations for all I/0 functions<br />

- declaration of <strong>the</strong> FILE structure<br />

- macros – stdin, stdout, stderr, EOF, NULL<br />

getc()<br />

fgetc(*fp++)<br />

getchar()<br />

putc()<br />

fputc(c,*fp++)<br />

putchar()<br />

ferror() NULL is zero<br />

clearerr() EOF is -1<br />

feof()<br />

/* stream_stat.c<br />

if nei<strong>the</strong>r flag is set, stat will equal zero<br />

if error is set, but not eof, stat equals 1<br />

if eof is set, but not error, stat equals 2<br />

if both flags are set, stat equals 3<br />

*/<br />

#include <br />

#define EOF_FLAG 1<br />

#define ERR_FLAG 2<br />

char stream_stat(FILE *fp)<br />

{<br />

char stat=0;<br />

if (ferror(fp))<br />

stat |= ERR_FLAG;<br />

if (feof(fp))<br />

stat |= EOF_FLAG;<br />

clearerr(fp);<br />

return stat;<br />

}<br />

! More I/O info:<br />

int getchar(void) = getc(stdin)<br />

char *gets(char *string)= reads a line from stdin<br />

/* gets = reads <strong>the</strong> linefeed & converts to a NULL */<br />

int printf(char *format)<br />

int putchar(char c) = putc(c, stdout)<br />

int puts(char *string) = writes a line to stdout<br />

int scanf(char *format)<br />

File I/O<br />

FILE *fopen(char *filename, char *type)<br />

type | Description<br />

"r" open existing text file for reading at beginning<br />

"w" create a new text file for writing<br />

"a" open an existing text file in append mode<br />

64

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!