Standard Library
## Learning Objectives
- Master common standard library functions
- Understand input/output functions
- Work with string functions
- Use memory and utility functions
## Standard Headers
| Header | Description |
|--------|-------------|
| `` | Input/output |
| `` | Memory, utilities |
| `` | String functions |
| `` | Character classification |
| `` | Math functions |
| `` | Date/time |
| `` | Assertions |
| `` | Type limits |
| `` | Float limits |
## stdio.h - Input/Output
### Printf Family
```c
#include
printf("Hello\n");
fprintf(fp, "Hello\n");
sprintf(buf, "Hello\n"); // To string
snprintf(buf, size, "Hello\n"); // Safe
```
### Scanf Family
```c
int x;
scanf("%d", &x);
fscanf(fp, "%d", &x);
sscanf(str, "%d", &x);
```
### Character I/O
```c
int getchar(void); // Read char from stdin
int putchar(int c); // Write char to stdout
int getc(FILE *fp); // Read char from file
int putc(int c, FILE *fp); // Write char to file
```
## stdlib.h - Utilities
### Memory Allocation
```c
void *malloc(size_t size);
void *calloc(size_t nmemb, size_t size);
void *realloc(void *ptr, size_t size);
void free(void *ptr);
```
### Program Control
```c
#include
exit(0); // Exit with success
exit(1); // Exit with failure
int atexit(void (*function)(void));
// Register function to call at exit
void abort(void); // Abnormal termination
```
### String Conversion
```c
int atoi(const char *str); // ASCII to int
long atol(const char *str); // ASCII to long
double atof(const char *str); // ASCII to float
// Safer versions
int strtol(const char *str, char **endptr, int base);
double strtod(const char *str, char **endptr);
```
### System
```c
#include
int system(const char *command); // Execute shell command
char *getenv(const char *name); // Get environment variable
```
### Sorting
```c
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
int arr[] = {3, 1, 4, 1, 5};
qsort(arr, 5, sizeof(int), compare);
```
### Binary Search
```c
void *bsearch(const void *key, const void *base,
size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
int key = 4;
int *result = (int*)bsearch(&key, arr, 5, sizeof(int), compare);
```
### Random Numbers
```c
#include
int rand(void);
void srand(unsigned int seed);
// 0 to RAND_MAX
int r = rand() % 100; // 0 to 99
```
### Absolute Value
```c
#include
int abs(int x);
long labs(long x);
```
## string.h - String Functions
### strlen
```c
#include
size_t strlen(const char *s);
```
### Copy Functions
```c
char *strcpy(char *dest, const char *src);
char *strncpy(char *dest, const char *src, size_t n);
void *memcpy(void *dest, const void *src, size_t n);
void *memmove(void *dest, const void *src, size_t n);
```
### Concatenation
```c
char *strcat(char *dest, const char *src);
char *strncat(char *dest, const char *src, size_t n);
```
### Comparison
```c
int strcmp(const char *s1, const char *s2);
int strncmp(const char *s1, const char *s2, size_t n);
int memcmp(const void *s1, const void *s2, size_t n);
```
### Search
```c
char *strchr(const char *s, int c); // Find character
char *strstr(const char *haystack, const char *needle); // Find substring
```
### Other
```c
void *memset(void *s, int c, size_t n); // Fill memory
char *strerror(int errnum); // Error message
size_t strcspn(const char *s, const char *reject); // Span until reject
```
## ctype.h - Character Classification
```c
#include
int isalpha(int c); // Letter
int isdigit(int c); // Digit
int isalnum(int c); // Letter or digit
int isspace(int c); // Whitespace
int isupper(int c); // Uppercase
int islower(int c); // Lowercase
int iscntrl(int c); // Control character
int tolower(int c); // To lowercase
int toupper(int c); // To uppercase
```
## math.h - Mathematical Functions
```c
#include
double sqrt(double x);
double pow(double x, double y);
double exp(double x);
double log(double x);
double log10(double x);
double sin(double x);
double cos(double x);
double tan(double x);
double ceil(double x); // Round up
double floor(double x); // Round down
double fabs(double x); // Absolute value
double M_PI; // pi constant
```
### Link with -lm
```bash
gcc program.c -lm
```
## time.h - Date and Time
```c
#include
time_t now = time(NULL); // Current time
printf("%s", ctime(&now));
struct tm *t = localtime(&now);
printf("%d-%02d-%02d\n", t->tm_year + 1900,
t->tm_mon + 1, t->tm_mday);
```
### Formatting
```c
#include
time_t now = time(NULL);
char buf[100];
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", localtime(&now));
printf("%s\n", buf);
```
## Common Patterns
### Safe String Copy
```c
char *safeCopy(char *dest, const char *src, size_t size) {
if (size == 0) return dest;
dest[0] = '\0';
strncat(dest, src, size - 1);
return dest;
}
```
### Parse Command Line Arguments
```c
int main(int argc, char *argv[]) {
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "-n") == 0) {
// Handle -n flag
} else {
// Handle filename
}
}
return 0;
}
```
### Read File into String
```c
#include
#include
char *readFile(const char *filename) {
FILE *fp = fopen(filename, "r");
if (!fp) return NULL;
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
rewind(fp);
char *content = malloc(size + 1);
if (!content) {
fclose(fp);
return NULL;
}
fread(content, 1, size, fp);
content[size] = '\0';
fclose(fp);
return content;
}
```
## Summary
- ``: printf, scanf, fprintf, fscanf, fopen, fclose
- ``: malloc, free, calloc, realloc, atoi, strtol, qsort, exit
- ``: strlen, strcpy, strncpy, strcat, strcmp, strncmp, memset, memcpy
- ``: isalpha, isdigit, isspace, toupper, tolower
- ``: sqrt, pow, sin, cos, ceil, floor (link with -lm)
- ``: time, localtime, strftime
- Always check function return values for errors
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →