Created
November 5, 2013 20:16
-
-
Save ardeshir/7325441 to your computer and use it in GitHub Desktop.
Little Lib of C++ functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* libtools.cpp - library of C++ procedures */ | |
#include <cstdio> | |
#include <cstring> | |
#include <cstdlib> | |
#include <cctype> | |
#define MAX_NAME 255 /* maximum length of program or file name */ | |
static char prog_name[MAX_NAME+1]; /* used in error messages */ | |
/* savename - record a program name for error messages */ | |
void savename(const char* name) { | |
if (strlen(name) <= MAX_NAME) | |
strcpy(prog_name, name); | |
} | |
/* fatal - print message and die */ | |
int fatal(const char* msg) { | |
if(prog_name[0] != '\0') | |
fprintf(stderr, "%s: ", prog_name); | |
fprintf(stderr, "%s\n", msg); | |
exit(1); | |
} | |
/* fatalf - format message, print it and die */ | |
int fatalf(const char *msg, const char *val) { | |
if(prog_name[0] != '\0') | |
fprintf(stderr, "%s: ", prog_name); | |
fprintf(stderr, msg, val); | |
putc('\n', stderr); | |
exit(1); | |
} | |
/* ckopen - open file; check for success */ | |
FILE *ckopen(const char *name, const char *mode) { | |
FILE *fp; | |
if((fp = fopen(name, mode)) == NULL) | |
fatalf("Cannot open %s. ", name); | |
return(fp); | |
} | |
/* ckalloc - allocate space; check for success */ | |
void *ckalloc(int amount) { | |
void *p; | |
if((p = malloc( (unsigned) amount)) == NULL) | |
fatal("Run out of memory."); | |
return(p); | |
} | |
/* strsame - tell whether two strings are identical */ | |
int strsame(char *s, char *t) { | |
return(strcmp(s, t) == 0); | |
} | |
/* strsave - save string s somewhere ; return address */ | |
char *strsave(char *s) { | |
void *p; | |
p = ckalloc(strlen(s)+1); /* +1 to hold \0 */ | |
return(strcpy((char *)p,s)); | |
} | |
/*****************/ | |
/* */ | |
/* main */ | |
/* */ | |
/*****************/ | |
int main(int argc, const char *argv[]) { | |
savename("libtools"); | |
int c; | |
FILE *fp = stdin; | |
if( argc > 1) | |
fp = fopen(argv[1], "r"); | |
while((c = getc(fp)) != EOF) | |
putc(c, stdout); | |
printf("Program: %s completed!\n", prog_name); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment