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 />

/* cat.c: – concatenate files */<br />

#include <br />

main(int argc, char *argv[])<br />

{<br />

FILE *fp;<br />

void filecopy(FILE *, FILE *);<br />

char *prog=argv[0]; /* program name for errors */<br />

}<br />

if (argc == 1) /* no args; copy standard input */<br />

filecopy(stdin, stdout);<br />

else<br />

while (--argc > 0)<br />

if ((fp=fopen(*++argv,"r")) == NULL)<br />

{<br />

fprintf(stderr, "%s: can't open %s\n", prog, *argv);<br />

exit(1);<br />

}<br />

else<br />

{<br />

filecopy(fp, stdout);<br />

fclose(fp);<br />

}<br />

if (ferror(stdout))<br />

{<br />

fprintf(stderr,"%s: error writing stdout\n", prog);<br />

exit(2);<br />

}<br />

exit(0);<br />

Line Input and Output<br />

/* getline.c: – read a line, return length*/<br />

#include <br />

int getline(char *line, int max)<br />

{<br />

if (fgets(line, max, stdin) == NULL)<br />

return 0;<br />

else<br />

return strlen(line);<br />

}<br />

Read and writing to strings is similar to files<br />

int sprintf(char *string, char *format, arg1, arg2, ...);<br />

int sscanf(char *string, char *format, argl, arg2, ...);<br />

Storage Management<br />

#include <br />

The functions malloc and calloc obtain blocks of memory dynamically.<br />

void *malloc(size t n); /* pointer to n bytes */<br />

void *calloc(size t n, size t size); /* n objects */<br />

int *ip;<br />

ip = (int *) calloc (n, sizeof(int));<br />

void free(char *ptr) /* deallocate memory */<br />

char *realloc(char *ptr, unsigned size)<br />

/* preserve contents and change size */<br />

/* dynamic expanding of arrays */<br />

for (p=head; p!=NULL; p=p->next){<br />

67

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

Saved successfully!

Ooh no, something went wrong!