- 
<stdio.h>(Standard Buffered Input/Output)- Provides core functions for performing input and output operations, primarily using buffered streams (FILE*) for efficiency, including standard streams (stdin, stdout, stderr), file operations, and formatted I/O.
- FILE: Type representing a buffered file stream structure.
- stdin: (- FILE *) Macro representing the standard input stream.
- stdout: (- FILE *) Macro representing the standard output stream.
- stderr: (- FILE *) Macro representing the standard error stream.
- EOF: (int) Macro representing End-Of-File (typically -1).
- NULL: Macro representing a null pointer constant (often- (void*)0). Also defined in other headers like- <stdlib.h>and- <stddef.h>.
- size_t: Unsigned integer type for object sizes, counts. Also defined in- <stddef.h>,- <stdlib.h>,- <string.h>.
- int printf(const char *format, ...): Print formatted string output to- stdout. Returns number of characters written or negative on error.
- int fprintf(FILE *stream, const char *format, ...): Print formatted string output to the specified- stream. Returns number of characters written or negative on error.
- int snprintf(char *str, size_t size, const char *format, ...): Print formatted output to the character string- str, writing at most- sizebytes (including null terminator). Safer alternative to- sprintf. Returns number of characters that would have been written (excluding null) if- sizewas large enough, or negative on error.
- int sprintf(char *str, const char *format, ...): UNSAFE! Print formatted output to the character string- str. No bounds checking! Can easily cause buffer overflows. Returns number of characters written (excluding null).
- int scanf(const char *format, ...): Read formatted input from- stdin. Returns number of items successfully assigned or- EOF.
- int fscanf(FILE *stream, const char *format, ...): Read formatted input from the specified- stream. Returns number of items successfully assigned or- EOF.
- int sscanf(const char *str, const char *format, ...): Read formatted input from the character string- str. Returns number of items successfully assigned or- EOF.
- FILE *fopen(const char *pathname, const char *mode): Open the file specified by- pathnamewith the given- mode(e.g., "r", "w", "a", "rb", "wb", "ab", "+ variants"). Returns- FILE *stream or- NULLon error (check- errno).
- int fclose(FILE *stream): Close the specified file- stream, flushing any buffered data. Returns 0 on success,- EOFon error.
- size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream): Read- nmembitems, each- sizebytes long, from- streaminto the buffer- ptr. Used for binary input. Returns number of items successfully read (may be less than- nmembat EOF or error).
- size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream): Write- nmembitems, each- sizebytes long, from buffer- ptrto- stream. Used for binary output. Returns number of items successfully written (may be less than- nmembon error).
- char *fgets(char *s, int size, FILE *stream): Read at most- size-1characters from- streaminto the buffer- s. Stops on newline (which is included) or EOF. Null-terminates- s. Safer than- gets. Returns- son success,- NULLon EOF/error.
- int fputs(const char *s, FILE *stream): Write the null-terminated string- sto- stream. Does not write the null terminator or add a newline. Returns non-negative on success,- EOFon error.
- int puts(const char *s): Write the null-terminated string- sand a trailing newline to- stdout. Returns non-negative on success,- EOFon error.
- int fgetc(FILE *stream): Read the next character from- streamas an- unsigned charcast to an- int. Returns the character or- EOFon end-of-file or error.
- int getc(FILE *stream): Similar to- fgetc, potentially implemented as a macro (beware side effects in arguments).
- int getchar(void): Equivalent to- getc(stdin). Read next char from standard input.
- int fputc(int c, FILE *stream): Write the character- c(cast to- unsigned char) to- stream. Returns the character written or- EOFon error.
- int putc(int c, FILE *stream): Similar to- fputc, potentially implemented as a macro.
- int putchar(int c): Equivalent to- putc(c, stdout). Write char- cto standard output.
- int fflush(FILE *stream): Flush the output buffer of the- stream. If- streamis- NULL, flush all output streams. Returns 0 on success,- EOFon error.
- int fseek(FILE *stream, long offset, int whence): Set the file position indicator for- stream.- whenceis- SEEK_SET(start),- SEEK_CUR(current),- SEEK_END(end). Returns 0 on success, non-zero on error.
- long ftell(FILE *stream): Return the current value of the file position indicator for- stream, or -1L on error.
- void rewind(FILE *stream): Equivalent to- fseek(stream, 0L, SEEK_SET); clearerr(stream). Resets position to start and clears error/EOF flags.
- int feof(FILE *stream): Check if the end-of-file indicator for- streamis set. Returns non-zero if EOF, 0 otherwise.
- int ferror(FILE *stream): Check if the error indicator for- streamis set. Returns non-zero if error, 0 otherwise.
- void clearerr(FILE *stream): Clear the end-of-file and error indicators for- stream.
- void perror(const char *s): Print the string- s, a colon, a space, and the system error message corresponding to the current- errnovalue to- stderr.
- int remove(const char *pathname): Delete the file specified by- pathname. Returns 0 on success, non-zero on error.
- int rename(const char *oldpath, const char *newpath): Rename/move the file- oldpathto- newpath. Returns 0 on success, non-zero on error.
- char *gets(char *s): UNSAFE! EXTREMELY DANGEROUS! Reads a line from stdin into- swithout any bounds checking. Never use this function. Removed in C11.
- int setvbuf(FILE *stream, char *buf, int mode, size_t size): Set the buffering mode (- _IOFBF,- _IOLBF,- _IONBF) and optionally buffer (- buf,- size) for- stream. Must be called after opening but before I/O. Returns 0 on success.
- char *tmpnam(char *s): UNSAFE! Generates a unique temporary filename. Prone to race conditions between generation and file creation. Use- mkstempinstead.
- FILE *tmpfile(void): Creates and opens a unique temporary binary file ("wb+") that is automatically removed when closed or program terminates. Returns- FILE*or- NULL. Safer than- tmpnam.
 
- Provides core functions for performing input and output operations, primarily using buffered streams (
- 
<stdlib.h>(Standard Library Utilities)- Provides functions for memory allocation, process control, string conversions, pseudo-random number generation, searching, sorting, and other general utilities.
- size_t: Unsigned integer type for object sizes, counts. Also defined in- <stddef.h>,- <stdio.h>,- <string.h>.
- NULL: Macro representing a null pointer constant. Also defined elsewhere.
- void *malloc(size_t size): Allocate- sizebytes of raw, uninitialized memory block dynamically on the heap; returns pointer to allocated memory or- NULLon failure.
- void free(void *ptr): Deallocate the memory block pointed to by- ptr(which must have been returned by- malloc,- calloc, or- realloc, or be- NULL). Passing- NULLis safe and does nothing.
- void *calloc(size_t nmemb, size_t size): Allocate memory for an array of- nmembelements of- sizebytes each, initialize allocated memory to zero; returns pointer or- NULLon failure.
- void *realloc(void *ptr, size_t size): Change the size of the previously allocated memory block at- ptrto- sizebytes. May move the block. Returns new pointer or- NULLon failure. If- ptris- NULL, equivalent to- malloc(size). If- sizeis 0, may free- ptror return unique pointer (behavior varies, best to use- freeexplicitly).
- void exit(int status): Terminate the calling process normally. Performs cleanup (flushes stdio, calls- atexithandlers) then calls- _exit(status).- statusis exit code (0 or- EXIT_SUCCESSfor success,- EXIT_FAILUREor non-zero for failure).
- void abort(void): Cause abnormal process termination (often by raising- SIGABRT). May not perform standard cleanup.
- int atexit(void (*func)(void)): Register a function- functo be called automatically at normal program termination (- exit()or return from- main). Returns 0 on success.
- long strtol(const char *nptr, char **endptr, int base): Convert the initial part of the string- nptrto a- long intvalue according to the given- base(0, 2-36). Stores pointer to first invalid char in- *endptr(if not- NULL). Robust error checking via- errnoand- endptr.
- unsigned long strtoul(const char *nptr, char **endptr, int base): Convert the initial part of the string- nptrto an- unsigned long int. Similar robustness to- strtol.
- double strtod(const char *nptr, char **endptr): Convert the initial part of the string- nptrto a- double. Similar robustness. Robust error checking via- errnoand- endptr.
- int rand(void): Return a pseudo-random integer between 0 and- RAND_MAX. Low quality PRNG, not suitable for cryptography or serious simulations.
- void srand(unsigned int seed): Seed the pseudo-random number generator used by- rand()with- seed. Often seeded with- time(NULL).
- void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)): Sort an array- baseof- nmembelements each of- sizebytes, using the- comparfunction for comparison.- compar(a, b)should return <0 if- a<b, 0 if- a==b, >0 if- a>b.
- void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)): Perform binary search for- keyin the sorted array- base. Returns pointer to matching element or- NULLif not found.- comparfunction same as for- qsort.
- char *getenv(const char *name): Get the value of an environment variable- name. Returns pointer to value string (do not modify) or- NULLif not found.
- int system(const char *command): Execute a shell- command. Returns command's exit status or -1 on error. Warning: Security risks if- commandstring contains untrusted user input (potential command injection). If- commandis- NULL, returns non-zero if shell is available, 0 otherwise.
- int abs(int j): Compute absolute value of integer- j. (Behavior undefined for- INT_MIN).
- long labs(long j): Compute absolute value of long integer- j. (Behavior undefined for- LONG_MIN).
- div_t div(int numerator, int denominator): Compute integer division- numerator / denominator. Returns- div_tstruct containing- quot(quotient) and- rem(remainder). Handles signs correctly.
- ldiv_t ldiv(long numerator, long denominator): Long integer version of- div. Returns- ldiv_tstruct.
- int atoi(const char *nptr): UNSAFE (limited)! Convert initial part of string- nptrto- int. No error checking (returns 0 on error, indistinguishable from valid 0). Use- strtolfor robustness.
- long atol(const char *nptr): UNSAFE (limited)! Convert initial part of string- nptrto- long. No error checking. Use- strtol.
- double atof(const char *nptr): UNSAFE (limited)! Convert initial part of string- nptrto- double. Limited error checking. Use- strtodfor robustness.
- char *mktemp(char *template): UNSAFE! Creates a unique temporary filename based on- template(which must end in XXXXXX). Modifies- template. Prone to race conditions. Use- mkstemp. Removed in POSIX.1-2008.
- int mkstemp(char *template): (Requires- <unistd.h>typically, but closely related to- mktemp). Creates and opens a unique temporary file based on- template(ending in XXXXXX), modifying- templateto the actual filename. Returns file descriptor. Much safer than- mktemp.
- EXIT_SUCCESS: Macro expanding to an integer constant indicating successful termination (usually 0).
- EXIT_FAILURE: Macro expanding to an integer constant indicating unsuccessful termination (usually 1).
- RAND_MAX: Macro defining the maximum value returned by- rand().
 
- 
<string.h>(String and Memory Operations)- Provides functions for manipulating arrays of characters (strings) and arbitrary blocks of memory.
- size_t: Unsigned integer type for object sizes, counts. Also defined elsewhere.
- NULL: Macro representing a null pointer constant. Also defined elsewhere.
- void *memcpy(void *dest, const void *src, size_t n): Copy- nbytes from memory area- srcto memory area- dest. Behavior is undefined if- srcand- destoverlap. Returns- dest.
- void *memmove(void *dest, const void *src, size_t n): Copy- nbytes from memory area- srcto memory area- dest. Areas may overlap (handles overlap correctly). Returns- dest.
- void *memset(void *s, int c, size_t n): Fill the first- nbytes of the memory area- swith the constant byte- c(converted to- unsigned char). Returns- s. Often used to zero memory (e.g.,- memset(ptr, 0, size)).
- int memcmp(const void *s1, const void *s2, size_t n): Compare the first- nbytes of memory areas- s1and- s2. Returns an integer less than, equal to, or greater than zero if- s1is found, respectively, to be less than, to match, or be greater than- s2.
- void *memchr(const void *s, int c, size_t n): Scan the first- nbytes of memory area- sfor the first instance of byte- c(converted to- unsigned char). Returns pointer to the byte or- NULLif not found.
- size_t strlen(const char *s): Calculate the length of the null-terminated string- s(excluding the null byte).
- char *strcpy(char *dest, const char *src): UNSAFE! Copy the null-terminated string- srcto- dest(including null terminator). No bounds checking! High risk of buffer overflows. Use- strncpy(carefully) or- snprintf. Returns- dest.
- char *strncpy(char *dest, const char *src, size_t n): Copy at most- nbytes from string- srcto- dest. Warning: If- strlen(src) >= n,- destwill not be null-terminated. Always ensure null termination manually if needed (e.g.,- dest[n-1] = '\0';if- n > 0). Returns- dest.
- char *strcat(char *dest, const char *src): UNSAFE! Append the null-terminated string- srcto the end of- dest. No bounds checking on- dest! High risk of buffer overflows. Use- strncat. Returns- dest.
- char *strncat(char *dest, const char *src, size_t n): Append at most- nbytes from string- srcto- dest, plus a null terminator. Safer than- strcat, but requires- destto have enough space for its original content,- nbytes from- src, and the null terminator. Always null-terminates (unlike- strncpy). Returns- dest.
- int strcmp(const char *s1, const char *s2): Compare two null-terminated strings- s1and- s2lexicographically. Returns <0, 0, or >0.
- int strncmp(const char *s1, const char *s2, size_t n): Compare at most- nbytes (or until a null terminator) of strings- s1and- s2. Returns <0, 0, or >0.
- char *strchr(const char *s, int c): Find the first occurrence of the character- c(converted to- char) in the null-terminated string- s. Returns pointer to the character in- sor- NULLif not found.
- char *strrchr(const char *s, int c): Find the last occurrence of the character- c(converted to- char) in the null-terminated string- s. Returns pointer or- NULL.
- char *strstr(const char *haystack, const char *needle): Find the first occurrence of the null-terminated substring- needlewithin the null-terminated string- haystack. Returns pointer to the beginning of the substring in- haystackor- NULL.
- size_t strspn(const char *s, const char *accept): Calculate the length of the initial segment of- swhich consists only of characters found in- accept.
- size_t strcspn(const char *s, const char *reject): Calculate the length of the initial segment of- swhich consists only of characters not found in- reject.
- char *strpbrk(const char *s, const char *accept): Find the first character in- sthat matches any character specified in- accept. Returns pointer to the character or- NULL.
- char *strtok(char *str, const char *delim): UNSAFE (Stateful/Not Reentrant)! Find tokens (substrings separated by- delim) in- str. Modifies- strby inserting null bytes. Pass- stron first call,- NULLon subsequent calls to get next token. Not thread-safe. Use- strtok_r(POSIX) if available. Returns pointer to token or- NULL.
- char *strerror(int errnum): Return a pointer to a string describing the error code- errnum. The string may be statically allocated and overwritten by subsequent calls (potentially not thread-safe depending on implementation). Use- strerror_r(POSIX) for thread-safety.
 
- 
<stddef.h>(Standard Definitions)- Defines several fundamental types and macros used throughout the standard library, particularly related to sizes and pointers.
- size_t: Unsigned integer type returned by- sizeofoperator, used for object sizes, memory allocation, array indexing, loop counts.
- ptrdiff_t: Signed integer type capable of storing the result of subtracting two pointers.
- NULL: Macro representing a null pointer constant (often- (void*)0). Standard definition.
- offsetof(type, member): Macro that calculates the byte offset of a- memberwithin a- structor- unionof- type. Result is of type- size_t.
 
- 
<stdint.h>(Integer Types - C99 onwards)- Defines integer types with specific widths and other properties, promoting portability and clarity when exact sizes are needed.
- int8_t,- uint8_t: Signed/Unsigned 8-bit integer types (optional).
- int16_t,- uint16_t: Signed/Unsigned 16-bit integer types (optional).
- int32_t,- uint32_t: Signed/Unsigned 32-bit integer types (optional).
- int64_t,- uint64_t: Signed/Unsigned 64-bit integer types (optional).
- int_least8_t,- uint_least8_t: Smallest signed/unsigned type with at least 8 bits. (Similar for 16, 32, 64).
- int_fast8_t,- uint_fast8_t: Fastest signed/unsigned type with at least 8 bits. (Similar for 16, 32, 64).
- intptr_t,- uintptr_t: Signed/Unsigned integer types guaranteed to be large enough to hold a- void*pointer without loss (optional).
- intmax_t,- uintmax_t: Largest supported signed/unsigned integer types.
- INT8_MIN,- INT8_MAX,- UINT8_MAX: Macros for min/max values of fixed-width types (similar for 16, 32, 64).
- SIZE_MAX: Macro defining the maximum value for- size_t.
 
- 
<errno.h>(System Error Numbers)- Defines the integer variable errnoand macros for error codes reported by system calls and some library functions.
- int errno: External integer variable (thread-local in modern multi-threaded environments) holding the last error code set by a failing system call or library function. Must include- <errno.h>to use it. Value is only meaningful immediately after a function indicates failure (e.g., returns -1 or NULL).
- Common errnovalue macros (represent error conditions):- EPERM: Operation not permitted.
- ENOENT: No such file or directory.
- EIO: Input/output error (often hardware or low-level).
- E2BIG: Argument list too long.
- EBADF: Bad file descriptor.
- EAGAIN/- EWOULDBLOCK: Resource temporarily unavailable / Operation would block (non-blocking I/O). Try again later.
- ENOMEM: Not enough memory (Out of memory).
- EACCES: Permission denied.
- EFAULT: Bad address (invalid pointer passed).
- EBUSY: Device or resource busy.
- EEXIST: File exists.
- EINVAL: Invalid argument provided to function.
- ENOSPC: No space left on device.
- EPIPE: Broken pipe (write to pipe/socket with no reader).
- EINTR: Interrupted system call (often by a signal, may require retrying).
 
 
- Defines the integer variable 
- 
<unistd.h>(POSIX Operating System API)- Provides access to the POSIX operating system API, including I/O primitives (file descriptors), process control, user/group IDs, filesystem operations, and various system configuration constants. (Not part of standard C, but core to POSIX systems like Linux, macOS).
- ssize_t: Signed integer type for byte counts returned by functions like- read,- write,- recv(can hold -1 for errors). Defined in- <sys/types.h>usually, often included.
- off_t: Signed integer type for file sizes and offsets. Defined in- <sys/types.h>.
- pid_t: Signed integer type for process IDs (PID) and process group IDs. Defined in- <sys/types.h>.
- uid_t: Integer type for user IDs (UID). Defined in- <sys/types.h>.
- gid_t: Integer type for group IDs (GID). Defined in- <sys/types.h>.
- int read(int fd, void *buf, size_t count): Read up to- countbytes from file descriptor- fdinto- buf. Returns bytes read (0 on EOF), or -1 on error (check- errno).
- int write(int fd, const void *buf, size_t count): Write up to- countbytes from- bufto file descriptor- fd. Returns bytes written, or -1 on error (check- errno).
- int close(int fd): Close the file descriptor- fd. Returns 0 on success, -1 on error.
- off_t lseek(int fd, off_t offset, int whence): Reposition the read/write file offset of the open file descriptor- fd.- whenceis- SEEK_SET,- SEEK_CUR,- SEEK_END. Returns resulting offset from beginning of file, or -1 on error.
- pid_t fork(void): Create a new child process which is a duplicate of the calling (parent) process. Returns child's PID in parent, 0 in child, -1 on error.
- int execve(const char *pathname, char *const argv[], char *const envp[]): Replace the current process image with a new one loaded from- pathname.- argvis the argument list (null-terminated array),- envpis the environment (null-terminated array). Does not return on success. Returns -1 on error. The core- execfunction.
- int execv(const char *pathname, char *const argv[]): Like- execve, uses current environment.
- int execvp(const char *file, char *const argv[]): Like- execv, but searches- PATHenvironment variable for- fileif it doesn't contain a slash. Common variant.
- int execl(const char *pathname, const char *arg, ... /*, (char *) NULL */): List-based variant of- exec, takes arguments as separate- const char*parameters, terminated by- NULL. Uses current environment.
- int execlp(const char *file, const char *arg, ... /*, (char *) NULL */): List-based variant like- execl, but searches- PATHlike- execvp.
- pid_t getpid(void): Get the process ID (PID) of the calling process.
- pid_t getppid(void): Get the parent process ID (PPID) of the calling process.
- uid_t getuid(void): Get the real user ID (UID) of the calling process.
- uid_t geteuid(void): Get the effective user ID (EUID) of the calling process.
- gid_t getgid(void): Get the real group ID (GID) of the calling process.
- gid_t getegid(void): Get the effective group ID (EGID) of the calling process.
- void _exit(int status): Terminate the calling process immediately without calling exit handlers (- atexit) or flushing stdio buffers.- statusis exit code (low 8 bits available to parent via- wait). Usually called by- exit().
- unsigned int alarm(unsigned int seconds): Arrange for- SIGALRMsignal to be delivered to the process in- seconds. If- secondsis 0, cancels pending alarm. Returns seconds remaining on previous alarm, or 0.
- int pause(void): Suspend the process until a signal is caught whose action is to terminate or call a handler. Returns -1 with- errnoset to- EINTR.
- unsigned int sleep(unsigned int seconds): Suspend execution for the specified number of- seconds, or until a signal is delivered that terminates the process or triggers a handler. Returns seconds left unslept (if interrupted), or 0.
- int usleep(useconds_t usec): DEPRECATED (in POSIX.1-2001, removed in 2008). Suspend execution for- usecmicroseconds. Use- nanosleepinstead. May interact poorly with signals.
- int pipe(int pipefd[2]): Create a pipe, a unidirectional data channel.- pipefd[0]is for reading,- pipefd[1]is for writing. Returns 0 on success, -1 on error.
- int dup(int oldfd): Duplicate an existing file descriptor- oldfd, returning the lowest unused non-negative descriptor. Returns new fd or -1.
- int dup2(int oldfd, int newfd): Duplicate- oldfdto- newfd, closing- newfdfirst if necessary. If- oldfd==- newfd, does nothing. Returns- newfdor -1.
- int unlink(const char *pathname): Remove a name (link) from the filesystem. If it's the last link and no processes have the file open, the file data is deleted. Used to delete files. Returns 0 on success, -1 on error.
- int rmdir(const char *pathname): Remove an empty directory. Returns 0 on success, -1 on error.
- int chdir(const char *path): Change the current working directory to- path. Returns 0 on success, -1 on error.
- char *getcwd(char *buf, size_t size): Copy the absolute pathname of the current working directory to- buf(up to- sizebytes). If- bufis- NULL, allocates buffer (needs- free). Returns- bufor- NULLon error.
- char *getwd(char *buf): UNSAFE! DEPRECATED! Get current working directory into- buf. Cannot specify buffer size, potential overflow. Use- getcwd.
- int chown(const char *pathname, uid_t owner, gid_t group): Change the owner and group of a file specified by- pathname. Use -1 for owner/group to leave unchanged. Returns 0 on success, -1 on error. (- lchownchanges symlink itself,- fchownuses fd).
- int access(const char *pathname, int mode): Check user's permissions for a file.- modeis bitwise OR of- R_OK,- W_OK,- X_OK(test permissions), or- F_OK(test existence). Warning: Potential Time-of-check to time-of-use (TOCTOU) race condition security vulnerability. Returns 0 if access allowed, -1 otherwise.
- long sysconf(int name): Get system configuration values at runtime (e.g.,- _SC_PAGESIZE,- _SC_NPROCESSORS_ONLN). Returns value or -1 on error.
- int isatty(int fd): Check if file descriptor- fdrefers to a terminal. Returns 1 if it is, 0 otherwise (setting- errnoif error occurs).
- int link(const char *oldpath, const char *newpath): Create a new hard link- newpathfor the existing file- oldpath. Returns 0 on success, -1 on error.
- int symlink(const char *target, const char *linkpath): Create a symbolic link named- linkpathcontaining the string- target. Returns 0 on success, -1 on error.
- ssize_t readlink(const char *pathname, char *buf, size_t bufsiz): Read the value of a symbolic link- pathnameinto- buf(up to- bufsizbytes). Does not null-terminate- buf. Returns bytes read or -1.
 
- 
<fcntl.h>(File Control Operations)- Defines functions and constants for manipulating file descriptors, such as opening files (open), modifying their properties (fcntl), and locking. (POSIX header).
- int open(const char *pathname, int flags, ... /* mode_t mode */): Open or create a file, returning a non-negative file descriptor (- fd).- flagsis bitwise OR of access modes (- O_RDONLY,- O_WRONLY,- O_RDWR) and creation/status flags (- O_CREAT,- O_TRUNC,- O_APPEND,- O_NONBLOCK,- O_CLOEXEC, etc.). Optional- modeargument (e.g.,- 0644) is required only when- O_CREATis specified, sets initial permissions (modified by umask). Returns fd or -1 on error.
- int creat(const char *pathname, mode_t mode): DEPRECATED. Equivalent to- open(pathname, O_WRONLY|O_CREAT|O_TRUNC, mode). Use- opendirectly.
- int fcntl(int fd, int cmd, ... /* arg */): Perform various operations (- cmd) on file descriptor- fd. Common commands:- F_DUPFD: Duplicate fd (like- dup, but to lowest >=- arg).
- F_GETFD/- F_SETFD: Get/set fd flags (e.g.,- FD_CLOEXEC).- argis int.
- F_GETFL/- F_SETFL: Get/set file status flags (e.g.,- O_APPEND,- O_NONBLOCK).- argis int.
- F_GETLK/- F_SETLK/- F_SETLKW: Get/Set/Set-and-wait for file locks.- argis- struct flock *.
 
- Common open/fcntlflags:- O_RDONLY: Open for reading only.
- O_WRONLY: Open for writing only.
- O_RDWR: Open for reading and writing.
- O_APPEND: Append data to the end of the file.
- O_CREAT: Create file if it does not exist.
- O_EXCL: Used with- O_CREAT, ensures- openfails if file exists (atomic check).
- O_TRUNC: Truncate existing file to zero length if opened for writing.
- O_NONBLOCK: Open in non-blocking mode (I/O calls return immediately, possibly with- EAGAIN/- EWOULDBLOCK).
- O_CLOEXEC: Set the close-on-exec flag for the new file descriptor (atomically). Prevents fd leakage across- exec.
 
- FD_CLOEXEC: File descriptor flag (for- F_GETFD/- F_SETFD) indicating fd should be closed automatically upon- exec.
 
- Defines functions and constants for manipulating file descriptors, such as opening files (
- 
<sys/stat.h>(File Status and Information)- Defines the statstructure used to hold file metadata, functions to retrieve this information (stat,fstat,lstat), and functions for creating directories/FIFOs and changing file modes. (POSIX header).
- struct stat: Structure holding file metadata (device ID, inode number, mode/permissions, link count, user ID, group ID, size, access time, modification time, status change time, block size, block count).
- mode_t: Integer type for file modes/permissions. Defined in- <sys/types.h>.
- int stat(const char *pathname, struct stat *statbuf): Get file status for- pathname(follows symbolic links) and store it in- statbuf. Returns 0 on success, -1 on error.
- int fstat(int fd, struct stat *statbuf): Get file status for the open file descriptor- fd. Returns 0 on success, -1 on error.
- int lstat(const char *pathname, struct stat *statbuf): Get file status for- pathname. If- pathnameis a symbolic link, stats the link itself, not the file it points to. Returns 0 on success, -1 on error.
- int mkdir(const char *pathname, mode_t mode): Create a new directory named- pathnamewith specified initial- mode(permissions, modified by the process's umask). Returns 0 on success, -1 on error.
- int chmod(const char *pathname, mode_t mode): Change the permissions (mode) of file- pathname. Returns 0 on success, -1 on error. (- fchmodoperates on an fd).
- mode_t umask(mode_t mask): Set the process's file mode creation mask and return the previous mask. Bits set in- maskare cleared from the mode specified in- openor- mkdir.
- File type macros (for testing st_modefield):- S_ISREG(m): Is it a regular file?
- S_ISDIR(m): Is it a directory?
- S_ISCHR(m): Is it a character device?
- S_ISBLK(m): Is it a block device?
- S_ISFIFO(m): Is it a FIFO (named pipe)?
- S_ISLNK(m): Is it a symbolic link? (Use- lstatto get mode for link itself).
- S_ISSOCK(m): Is it a socket?
 
- Permission bits (for st_modefield andmodearguments toopen/chmod/mkdir):- S_IRUSR,- S_IWUSR,- S_IXUSR: User (owner) read, write, execute.
- S_IRGRP,- S_IWGRP,- S_IXGRP: Group read, write, execute.
- S_IROTH,- S_IWOTH,- S_IXOTH: Others read, write, execute.
- S_ISUID: Set-user-ID bit.
- S_ISGID: Set-group-ID bit.
- S_ISVTX: Sticky bit.
 
 
- Defines the 
- 
<sys/types.h>(Primitive System Data Types)- Defines various basic data types used in system calls and other POSIX headers. Often included implicitly by other headers like <unistd.h>or<sys/stat.h>. (POSIX header).
- size_t: Unsigned integer type for sizes. Also in- <stddef.h>.
- ssize_t: Signed integer type for byte counts or errors (-1).
- pid_t: Signed integer type for process IDs (PID) and process group IDs.
- uid_t: Integer type for user IDs (UID).
- gid_t: Integer type for group IDs (GID).
- off_t: Signed integer type for file sizes and offsets (used by- lseek).
- mode_t: Integer type for file modes/permissions (used by- stat,- chmod,- mkdir,- open).
- dev_t: Type for device IDs (- st_dev).
- ino_t: Type for inode numbers (- st_ino).
- nlink_t: Type for link counts (- st_nlink).
- time_t: Type for time in seconds. Also in- <time.h>.
 
- Defines various basic data types used in system calls and other POSIX headers. Often included implicitly by other headers like 
- 
<signal.h>(Signal Handling)- Provides facilities for handling asynchronous signals (interrupts, exceptions, notifications) that can be delivered to a process.
- sig_atomic_t: Integer type that can be accessed atomically, suitable for simple communication with signal handlers (assignments must be single, indivisible operations).
- sigset_t: Type representing a set of signals (used for blocking/unblocking).
- struct sigaction: Structure used with- sigactionto specify signal handling details (handler function, signal mask to block during handler execution, flags).
- typedef void (*sighandler_t)(int);(Conceptual type, actual definition varies) The type of a signal handler function, taking the signal number as an argument.
- int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact): Examine and change the action for signal- signum.- actspecifies the new action,- oldact(if non-NULL) receives the previous action. The preferred, portable, and more powerful way to handle signals. Returns 0 on success, -1 on error.
- sighandler_t signal(int signum, sighandler_t handler): UNRELIABLE/NON-PORTABLE (historically). Set the disposition (handler) for signal- signum.- handlercan be- SIG_DFL(default),- SIG_IGN(ignore), or a function pointer. Semantics vary across systems (especially regarding handler re-installation). Use- sigactioninstead for reliable behavior. Returns previous handler or- SIG_ERRon error.
- int kill(pid_t pid, int sig): Send signal- sigto process- pid. Special- pidvalues: >0 (specific process), 0 (current process group), -1 (all processes with permission), <-1 (process group abs(pid)). Returns 0 on success, -1 on error.
- int raise(int sig): Send signal- sigto the calling process or thread. Equivalent to- kill(getpid(), sig). Returns 0 on success, non-zero on error.
- int sigemptyset(sigset_t *set): Initialize the signal set- setto be empty (exclude all signals). Returns 0 on success, -1 on error.
- int sigfillset(sigset_t *set): Initialize the signal set- setto be full (include all signals). Returns 0 on success, -1 on error.
- int sigaddset(sigset_t *set, int signum): Add signal- signumto the signal set- set. Returns 0 on success, -1 on error.
- int sigdelset(sigset_t *set, int signum): Remove signal- signumfrom the signal set- set. Returns 0 on success, -1 on error.
- int sigismember(const sigset_t *set, int signum): Test if- signumis a member of the signal set- set. Returns 1 if member, 0 if not, -1 on error.
- int sigprocmask(int how, const sigset_t *set, sigset_t *oldset): Examine and/or change the calling thread's signal mask (the set of currently blocked signals).- how:- SIG_BLOCK(add- setto mask),- SIG_UNBLOCK(remove- setfrom mask),- SIG_SETMASK(set mask to- set). If- oldsetis non-NULL, the previous mask is stored there. Returns 0 on success, -1 on error.
- int sigpending(sigset_t *set): Examine the set of signals that are currently blocked and pending for delivery to the calling thread. Stores the set in- set. Returns 0 on success, -1 on error.
- int sigsuspend(const sigset_t *mask): Atomically set the signal mask to- maskand suspend the process until a signal is caught (whose action isn't ignore) or terminates the process. Restores original mask on return. Returns -1 with- errno- EINTR.
- Handler Macros:
- SIG_DFL: Specifies the default action for the signal.
- SIG_IGN: Specifies that the signal should be ignored.
- SIG_ERR: Return value from- signalindicating an error.
 
- Common Signal Macros (partial list, behavior can vary):
- SIGHUP: Hangup detected on controlling terminal or death of controlling process.
- SIGINT: Interrupt from keyboard (Ctrl+C).
- SIGQUIT: Quit from keyboard (Ctrl+).
- SIGILL: Illegal Instruction.
- SIGABRT: Abort signal (e.g., from- abort()).
- SIGFPE: Floating point exception.
- SIGKILL: Kill signal (cannot be caught or ignored).
- SIGSEGV: Segmentation fault (invalid memory reference).
- SIGPIPE: Broken pipe (write to pipe/socket with no readers).
- SIGALRM: Timer signal from- alarm().
- SIGTERM: Termination signal (polite request to terminate).
- SIGCHLD: Child process stopped or terminated.
- SIGUSR1,- SIGUSR2: User-defined signals.
 
 
- 
<sys/wait.h>(Process Waiting)- Defines functions and macros for waiting for child processes to change state (terminate, stop) and retrieving information about their status. Essential for preventing zombie processes. (POSIX header).
- pid_t wait(int *wstatus): Wait for any child process to change state (terminate, stop, continue). Blocks until a child changes state. If- wstatusis not- NULL, stores status information there. Returns PID of the child whose state changed, or -1 on error (e.g., no children). Equivalent to- waitpid(-1, wstatus, 0).
- pid_t waitpid(pid_t pid, int *wstatus, int options): Wait for a specific child process or group of children to change state.- pid > 0: Wait for the specific child with PID- pid.
- pid == -1: Wait for any child process (like- wait).
- pid == 0: Wait for any child in the calling process's process group.
- pid < -1: Wait for any child in the process group- abs(pid).
- options: Bitwise OR of flags, e.g.,- WNOHANG(return immediately if no child has changed state),- WUNTRACED(also return if child is stopped),- WCONTINUED(also return if stopped child is continued).
- Returns PID of child, 0 (if WNOHANGand no change), or -1 on error.
 
- Wait status analysis macros (used with the wstatusvalue):- WIFEXITED(wstatus): Returns true (non-zero) if the child terminated normally (via- exit()or- returnfrom- main).
- WEXITSTATUS(wstatus): If- WIFEXITEDis true, returns the low 8 bits of the child's exit status.
- WIFSIGNALED(wstatus): Returns true if the child was terminated by a signal.
- WTERMSIG(wstatus): If- WIFSIGNALEDis true, returns the number of the signal that terminated the child.
- WIFSTOPPED(wstatus): Returns true if the child was stopped by a signal (requires- WUNTRACEDor- WCONTINUEDin- waitpid).
- WSTOPSIG(wstatus): If- WIFSTOPPEDis true, returns the number of the signal that stopped the child.
- WIFCONTINUED(wstatus): Returns true if the child was resumed by- SIGCONT(requires- WCONTINUED).
 
 
- 
<time.h>(Time and Date Functions)- Provides types and functions for manipulating time and date information.
- time_t: Arithmetic type capable of representing time (usually seconds since the Epoch: 00:00:00 UTC, Jan 1, 1970).
- struct tm: Structure holding broken-down calendar time:- int tm_sec: Seconds (0-60; 60 allows for leap seconds).
- int tm_min: Minutes (0-59).
- int tm_hour: Hours (0-23).
- int tm_mday: Day of the month (1-31).
- int tm_mon: Month (0-11; January = 0).
- int tm_year: Year since 1900.
- int tm_wday: Day of the week (0-6; Sunday = 0).
- int tm_yday: Day of the year (0-365).
- int tm_isdst: Daylight Saving Time flag (>0 if DST in effect, 0 if not, <0 if info unavailable).
 
- clock_t: Arithmetic type representing processor time.
- time_t time(time_t *tloc): Get current calendar time as- time_t(seconds since the Epoch). If- tlocis not- NULL, the value is also stored there. Returns current time or- (time_t)-1on error.
- struct tm *localtime(const time_t *timep): Convert- time_tvalue- timepinto broken-down time- struct tmexpressed in the system's local timezone. Warning: Returns pointer to a static internal buffer, which may be overwritten by subsequent calls to- localtimeor- gmtime. Not thread-safe. Use- localtime_r(POSIX) for thread-safety.
- struct tm *gmtime(const time_t *timep): Convert- time_tvalue- timepinto broken-down time- struct tmexpressed in Coordinated Universal Time (UTC, often called GMT). Warning: Returns pointer to static data, not thread-safe. Use- gmtime_r(POSIX).
- time_t mktime(struct tm *tm): Convert broken-down local time- struct tm(fields- tm_wdayand- tm_ydayare ignored, others normalized) into- time_tcalendar time value. Returns- time_tvalue or- (time_t)-1if it cannot be represented. Modifies the- tmstruct, filling in- tm_wdayand- tm_yday.
- size_t strftime(char *s, size_t maxsize, const char *format, const struct tm *tm): Format the broken-down time- tminto the string- s(up to- maxsizebytes, including null) according to- formatspecifiers (e.g.,- %Yyear,- %mmonth,- %dday,- %Hhour,- %Mmin,- %Ssec,- %Ztimezone name). Returns number of bytes written (excluding null) or 0 if- maxsizewas too small.
- char *asctime(const struct tm *tm): Convert- struct tminto a standard C string format (e.g., "Wed Jun 30 21:49:08 1993\n"). Warning: Returns pointer to static data, not thread-safe. Use- strftime.
- char *ctime(const time_t *timep): Convert- time_tinto a standard C string format (like- asctime). Equivalent to- asctime(localtime(timep)). Warning: Returns pointer to static data, not thread-safe.
- double difftime(time_t time1, time_t time0): Calculate the difference in seconds between two- time_tvalues (- time1-- time0), returned as a- double.
- clock_t clock(void): Return the processor time consumed by the program since invocation, measured in- clock_tunits. Divide by- CLOCKS_PER_SECto get seconds. May wrap. Quality/granularity varies.
- CLOCKS_PER_SEC: Macro defining the number of- clock_tticks per second.
 
- 
<sys/time.h>(Time Operations - High Resolution)- Provides structures and functions for more precise time measurements (microseconds). Often included by <time.h>on POSIX systems, but standard requires explicit include forgettimeofday. (POSIX header).
- struct timeval: Structure holding time with microsecond resolution:- time_t tv_sec: Seconds.
- suseconds_t tv_usec: Microseconds.
 
- struct timezone: OBSOLETE. Structure formerly used with- gettimeofdayfor timezone information. Do not use; pass- NULLfor the- tzargument.
- int gettimeofday(struct timeval *tv, struct timezone *tz): Get the current time as seconds and microseconds since the Epoch.- tzargument is obsolete and should be- NULL. Returns 0 on success, -1 on error. Still very common, though POSIX favors- clock_gettimefrom- <time.h>(if available with- CLOCK_REALTIME).
 
- Provides structures and functions for more precise time measurements (microseconds). Often included by 
- 
<math.h>(Mathematical Functions)- Provides common mathematical functions, primarily operating on doublefloating-point numbers.
- double sqrt(double x): Compute the non-negative square root of- x(- x >= 0).
- double pow(double base, double exp): Compute- baseraised to the power- exp(- base^exp). Handles various edge cases (0, infinity, NaN).
- double fabs(double x): Compute the absolute value of floating-point number- x. (- fabsffor- float,- fabslfor- long double).
- double fmod(double x, double y): Compute floating-point remainder of- x/y. Result has the same sign as- x.
- double exp(double x): Compute e (Euler's number, ~2.718) raised to the power- x(- e^x).
- double log(double x): Compute the natural logarithm (base e) of- x(- x > 0).
- double log10(double x): Compute the base-10 logarithm of- x(- x > 0).
- double sin(double x),- double cos(double x),- double tan(double x): Compute sine, cosine, tangent of- x(where- xis in radians).
- double asin(double x),- double acos(double x),- double atan(double x): Compute arc sine (- xin [-1,1]), arc cosine (- xin [-1,1]), arc tangent of- x. Results are in radians.
- double atan2(double y, double x): Compute arc tangent of- y/x, using the signs of- xand- yto determine the correct quadrant for the result (in radians, range [-pi, pi]).
- double ceil(double x): Round- xupward to the nearest integer value (returned as- double). "Ceiling".
- double floor(double x): Round- xdownward to the nearest integer value (returned as- double). "Floor".
- double round(double x): (C99) Round- xto the nearest integer value (returned as- double), rounding halfway cases away from zero.
- double trunc(double x): (C99) Round- xtoward zero to the nearest integer value (returned as- double).
- double hypot(double x, double y): (C99) Compute- sqrt(x*x + y*y)accurately, avoiding intermediate overflow/underflow.
- HUGE_VAL,- HUGE_VALF,- HUGE_VALL: Macros representing large positive floating-point values (often infinity). Used as error returns.
- INFINITY: (C99) Macro representing positive infinity (- floattype).
- NAN: (C99) Macro representing a "Not a Number" floating-point value (- floattype).
- fpclassify(x),- isfinite(x),- isinf(x),- isnan(x),- isnormal(x),- signbit(x): (C99) Macros for classifying floating-point values.
 
- Provides common mathematical functions, primarily operating on 
- 
<ctype.h>(Character Classification and Conversion)- Provides functions for testing characters against various classifications (digit, letter, whitespace, etc.) and for converting between uppercase and lowercase. Functions take intargument but typically operate on values representable asunsigned charorEOF.
- int isalnum(int c): Check if- cis alphanumeric (- isalphaor- isdigit).
- int isalpha(int c): Check if- cis an alphabetic character (- isupperor- islower).
- int iscntrl(int c): Check if- cis a control character.
- int isdigit(int c): Check if- cis a decimal digit ('0'-'9').
- int isgraph(int c): Check if- cis any printable character except space.
- int islower(int c): Check if- cis a lowercase letter.
- int isprint(int c): Check if- cis a printable character (including space).
- int ispunct(int c): Check if- cis a punctuation character (printable, not space or- isalnum).
- int isspace(int c): Check if- cis whitespace (space ' ', form feed '\f', newline '\n', carriage return '\r', horizontal tab '\t', vertical tab '\v').
- int isupper(int c): Check if- cis an uppercase letter.
- int isxdigit(int c): Check if- cis a hexadecimal digit ('0'-'9', 'a'-'f', 'A'-'F').
- int tolower(int c): Convert uppercase letter- cto lowercase. Returns- cunchanged if not uppercase.
- int toupper(int c): Convert lowercase letter- cto uppercase. Returns- cunchanged if not lowercase.
 
- Provides functions for testing characters against various classifications (digit, letter, whitespace, etc.) and for converting between uppercase and lowercase. Functions take 
- 
<stdbool.h>(Boolean Type and Values - C99 onwards)- Defines a boolean type and constants trueandfalsefor improved code clarity. Often implemented via macros that expand to integer types/values.
- bool: Macro expanding to the boolean type (- _Booltypically).
- true: Macro expanding to the boolean true value (typically 1).
- false: Macro expanding to the boolean false value (typically 0).
- __bool_true_false_are_defined: Macro defined to 1 when the header is included.
 
- Defines a boolean type and constants 
- 
<limits.h>(Limits of Fundamental Integer Types)- Defines macros specifying the limits (minimum and maximum values) for the standard fundamental integer types like char,int,short,long.
- CHAR_BIT: Number of bits in a- char.
- CHAR_MIN,- CHAR_MAX: Minimum/Maximum value for- char.
- SCHAR_MIN,- SCHAR_MAX: Minimum/Maximum value for- signed char.
- UCHAR_MAX: Maximum value for- unsigned char.
- SHRT_MIN,- SHRT_MAX: Minimum/Maximum value for- short int.
- USHRT_MAX: Maximum value for- unsigned short int.
- INT_MIN,- INT_MAX: Minimum/Maximum value for- int.
- UINT_MAX: Maximum value for- unsigned int.
- LONG_MIN,- LONG_MAX: Minimum/Maximum value for- long int.
- ULONG_MAX: Maximum value for- unsigned long int.
- LLONG_MIN,- LLONG_MAX: (C99) Minimum/Maximum value for- long long int.
- ULLONG_MAX: (C99) Maximum value for- unsigned long long int.
 
- Defines macros specifying the limits (minimum and maximum values) for the standard fundamental integer types like 
- 
<assert.h>(Debugging Assertions)- Provides the assertmacro, used for inserting run-time sanity checks during development.
- void assert(scalar expression): If the macro- NDEBUGis not defined at the point of inclusion of- <assert.h>,- assertevaluates- expression. If- expressionis false (evaluates to 0),- assertprints an error message (including the expression text, file name, and line number) to- stderrand then calls- abort(). If- NDEBUGis defined, the- assertmacro expands to nothing- ((void)0), effectively disabling the check for release builds.
 
- Provides the 
- 
<stdarg.h>(Variable Argument Lists)- Provides macros for implementing functions that accept a variable number of arguments (like printforscanf).
- va_list: Type suitable for holding information needed by- va_start,- va_arg, and- va_end.
- void va_start(va_list ap, last): Initializes- apfor use by- va_argand- va_end.- lastmust be the name of the last fixed parameter before the variable arguments (- ...). Must be called before first- va_arg.
- type va_arg(va_list ap, type): Expands to an expression that has the type and value of the next argument in the call.- apmust have been initialized by- va_start.- typeis the expected type of the next argument. Behavior undefined if no next argument or if- typeis incompatible. Modifies- ap.
- void va_end(va_list ap): Performs necessary cleanup for- apafter all arguments have been processed. Must be called before the function returns if- va_startwas called.
- void va_copy(va_list dest, va_list src): (C99) Creates a copy- destof the current variable argument list state- src. Useful if the list needs to be scanned more than once.- destmust also be passed to- va_end.
 
- Provides macros for implementing functions that accept a variable number of arguments (like 
- 
<sys/socket.h>(Core Socket Functions and Structures)- Defines the primary functions and structures for network socket programming (creating sockets, binding addresses, connecting, listening, sending, receiving). (POSIX/BSD Sockets API header).
- int socket(int domain, int type, int protocol): Create a communication endpoint (socket).- domain: Communication domain (e.g.,- AF_INETfor IPv4,- AF_INET6for IPv6,- AF_UNIXfor local).
- type: Communication semantics (e.g.,- SOCK_STREAMfor reliable stream/TCP,- SOCK_DGRAMfor datagram/UDP,- SOCK_RAWfor raw network protocol access). Add- SOCK_NONBLOCK,- SOCK_CLOEXEC(Linux extensions) for atomic setting.
- protocol: Specific protocol (usually 0 to select default for domain/type).
- Returns socket file descriptor (a small non-negative integer) or -1 on error.
 
- int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen): Assign a local address/port (- addr) to the socket- sockfd. Typically used on the server side before- listenor for specific client-side source address/port. Returns 0 on success, -1 on error.
- int listen(int sockfd, int backlog): Mark- sockfd(which must be of type- SOCK_STREAMor- SOCK_SEQPACKET) as a passive socket that will be used to accept incoming connection requests.- backlogsuggests the maximum queue length for pending connections. Returns 0 on success, -1 on error.
- int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen): For a listening socket- sockfd, extract the first connection request on the queue, create a new connected socket for this specific connection, and return its file descriptor. If- addrand- addrlenare non-NULL, they are filled with the address of the connecting peer (client).- addrlenis value-result: initialize it to- sizeof(*addr)before the call. Blocks by default until a connection arrives. Returns new socket fd or -1 on error. (Linux extension:- accept4adds flags like- SOCK_NONBLOCK,- SOCK_CLOEXEC).
- int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen): Initiate a connection on socket- sockfd(client side) to the server address specified by- addr. Returns 0 on success, -1 on error (connection may be asynchronous for non-blocking sockets).
- ssize_t send(int sockfd, const void *buf, size_t len, int flags): Send- lenbytes from- bufon a connected socket- sockfd.- flagsmodify behavior (e.g.,- MSG_NOSIGNALon Linux prevents- SIGPIPE). Returns number of bytes sent (can be less than- len) or -1 on error.
- ssize_t recv(int sockfd, void *buf, size_t len, int flags): Receive up to- lenbytes into- buffrom a connected socket- sockfd.- flagsmodify behavior (e.g.,- MSG_PEEKlooks at data without consuming). Returns number of bytes received, 0 if peer shut down connection gracefully, or -1 on error.
- ssize_t sendto(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen): Send- lenbytes from- bufon socket- sockfd(can be connected or unconnected, typically UDP) to the specific destination address- dest_addr. Returns bytes sent or -1.
- ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen): Receive up to- lenbytes into- buffrom socket- sockfd. If- src_addrand- addrlenare non-NULL, they are filled with the address of the sender.- addrlenis value-result. Returns bytes received, 0 on shutdown (if connected), or -1.
- int shutdown(int sockfd, int how): Gracefully disable sends and/or receives on a connected socket- sockfd.- how:- SHUT_RD(disable further receives),- SHUT_WR(disable further sends, sends FIN),- SHUT_RDWR(both).
- Returns 0 on success, -1 on error. Different from close()which releases the fd.
 
- int getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen): Get options for socket- sockfd.- levelindicates protocol level (e.g.,- SOL_SOCKET,- IPPROTO_TCP).- optnameis the option name (e.g.,- SO_REUSEADDR,- SO_ERROR,- TCP_NODELAY). Value stored in- optval, length in- optlen(value-result). Returns 0 or -1.
- int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen): Set options for socket- sockfd. Parameters similar to- getsockopt. Returns 0 or -1.
- struct sockaddr: Generic socket address structure (base type, contains- sa_family). Actual specific address structures (- sockaddr_in,- sockaddr_in6) are cast to this.
- struct sockaddr_storage: Generic socket address structure guaranteed to be large enough to hold any supported address type. Useful for writing protocol-agnostic code, avoids guessing buffer sizes needed for- acceptor- recvfrom. Contains- ss_family.
- socklen_t: Unsigned integer type used for socket address structure lengths (passed to- bind,- connect,- accept,- getsockname,- getpeername,- getsockopt,- setsockopt, etc.).
- Socket domain constants: AF_INET(IPv4),AF_INET6(IPv6),AF_UNIX/AF_LOCAL(Local IPC).
- Socket type constants: SOCK_STREAM(TCP),SOCK_DGRAM(UDP),SOCK_SEQPACKET(Sequenced, reliable datagrams),SOCK_RAW(Raw network layer access).
- Socket level constant (for getsockopt/setsockopt):SOL_SOCKET(generic socket options).
- Common socket options (optnameforSOL_SOCKET):SO_REUSEADDR(allow reuse of local address/port),SO_KEEPALIVE(enable keep-alive probes),SO_BROADCAST(allow sending broadcast messages),SO_ERROR(get pending error and clear),SO_RCVBUF/SO_SNDBUF(receive/send buffer sizes),SO_RCVTIMEO/SO_SNDTIMEO(receive/send timeouts).
- int getsockname(int sockfd, struct sockaddr *addr, socklen_t *addrlen): Get the local address/port bound to- sockfd.
- int getpeername(int sockfd, struct sockaddr *addr, socklen_t *addrlen): Get the remote address/port connected to- sockfd.
 
- 
<netinet/in.h>(Internet Address Family - IPv4/IPv6)- Defines structures and constants specific to the Internet Protocol suite (IPv4, IPv6), including socket address structures and byte order conversion functions. (POSIX/Sockets header).
- struct sockaddr_in: Socket address structure for IPv4. Contains:- sa_family_t sin_family: Address family (- AF_INET).
- in_port_t sin_port: Port number (in network byte order).
- struct in_addr sin_addr: IPv4 address (in network byte order).
 
- struct in_addr: Structure holding an IPv4 address. Contains:- uint32_t s_addr: The 32-bit IPv4 address (network byte order).
 
- struct sockaddr_in6: Socket address structure for IPv6. Contains:- sa_family_t sin6_family: Address family (- AF_INET6).
- in_port_t sin6_port: Port number (network byte order).
- uint32_t sin6_flowinfo: Flow information (network byte order).
- struct in6_addr sin6_addr: IPv6 address (network byte order).
- uint32_t sin6_scope_id: Scope ID (for link-local addresses).
 
- struct in6_addr: Structure holding an IPv6 address. Contains:- uint8_t s6_addr[16]: The 128-bit IPv6 address (network byte order array).
 
- uint16_t htons(uint16_t hostshort): Convert 16-bit value (- short) from host byte order to network byte order (Big Endian). "Host TO Network Short". Used for port numbers.
- uint32_t htonl(uint32_t hostlong): Convert 32-bit value (- long, typically) from host byte order to network byte order. "Host TO Network Long". Used for IPv4 addresses.
- uint16_t ntohs(uint16_t netshort): Convert 16-bit value from network byte order to host byte order. "Network TO Host Short".
- uint32_t ntohl(uint32_t netlong): Convert 32-bit value from network byte order to host byte order. "Network TO Host Long".
- Protocol number constants (for socketprotocolfield orgetprotobyname):IPPROTO_IP,IPPROTO_TCP,IPPROTO_UDP,IPPROTO_IPV6,IPPROTO_ICMP.
- INADDR_ANY: IPv4 wildcard address (0.0.0.0) for binding (use- htonl(INADDR_ANY)).
- INADDR_LOOPBACK: IPv4 loopback address (127.0.0.1) (use- htonl(INADDR_LOOPBACK)).
- in6addr_any: (- const struct in6_addr) IPv6 wildcard address (::) for binding.
- in6addr_loopback: (- const struct in6_addr) IPv6 loopback address (::1).
 
- 
<arpa/inet.h>(Internet Operations - String Conversion)- Provides functions for converting internet addresses between presentation (text string) format and network (binary) format. (POSIX/Sockets header).
- int inet_pton(int af, const char *src, void *dst): Convert IP address string- src(e.g., "192.0.2.1" or "2001:db8::1") in presentation format to binary network address format (stored in- dst, which should be a- struct in_addr *for- AF_INETor- struct in6_addr *for- AF_INET6).- afspecifies the address family. Modern, preferred, thread-safe, handles IPv4/IPv6. Returns 1 on success, 0 if- srcis not a valid address string for- af, -1 on error (- errnoset).
- const char *inet_ntop(int af, const void *src, char *dst, socklen_t size): Convert binary network address- src(- struct in_addr *or- struct in6_addr *) to presentation format string- dst.- sizeis the size of the- dstbuffer. Modern, preferred, thread-safe, handles IPv4/IPv6. Returns pointer to- dston success,- NULLon error (- errnoset, e.g.,- ENOSPCif- sizetoo small). Use- INET_ADDRSTRLENand- INET6_ADDRSTRLEN(defined in- <netinet/in.h>) for adequate buffer sizes.
- in_addr_t inet_addr(const char *cp): DEPRECATED/UNSAFE! Convert IPv4 address string- cp(dotted-decimal) to binary- uint32_tin network byte order. Returns- INADDR_NONE((- in_addr_t)-1) on error, but this is also a valid broadcast address (255.255.255.255), making error detection ambiguous. Only handles IPv4. Use- inet_pton.
- char *inet_ntoa(struct in_addr in): DEPRECATED/UNSAFE! Convert binary IPv4 address- in(network byte order) to dotted-decimal string. Warning: Returns pointer to a static internal buffer, which is overwritten by subsequent calls. Not thread-safe. Only handles IPv4. Use- inet_ntop.
 
- 
<netdb.h>(Network Database Operations - Hostname/Service Lookup)- Provides functions for translating between hostnames/service names and network addresses/port numbers, querying the network databases (like /etc/hosts, DNS,/etc/services). (POSIX/Sockets header).
- struct addrinfo: Structure used by- getaddrinfoto hold address information and hints:- int ai_flags: Input hints flags (e.g.,- AI_PASSIVE,- AI_CANONNAME,- AI_NUMERICHOST,- AI_NUMERICSERV).
- int ai_family: Address family (- AF_INET,- AF_INET6,- AF_UNSPEC).
- int ai_socktype: Socket type (- SOCK_STREAM,- SOCK_DGRAM, 0).
- int ai_protocol: Protocol (- IPPROTO_TCP,- IPPROTO_UDP, 0).
- socklen_t ai_addrlen: Length of- ai_addr.
- struct sockaddr *ai_addr: Pointer to socket address structure.
- char *ai_canonname: Pointer to canonical hostname (if- AI_CANONNAMErequested).
- struct addrinfo *ai_next: Pointer to next structure in linked list.
 
- int getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res): The modern, recommended function for network address and service translation. Resolves hostname (- node, e.g., "www.example.com" or IP string) and service name (- service, e.g., "http" or "80") into one or more- addrinfostructures, returned as a linked list via- res.- hintsprovides criteria (family, socktype, flags) for the lookup. Handles IPv4/IPv6 seamlessly based on system configuration and hints. The returned structures are suitable for passing directly to- socket,- bind,- connect. Returns 0 on success, non-zero error code (use- gai_strerrorto convert to string) on failure.
- void freeaddrinfo(struct addrinfo *res): Free the linked list of- addrinfostructures allocated and returned by- getaddrinfo. Must be called to prevent memory leaks.
- const char *gai_strerror(int errcode): Convert the error code returned by- getaddrinfointo a human-readable string.
- struct hostent *gethostbyname(const char *name): DEPRECATED. Look up host- name(hostname or IPv4 dotted-decimal). Returns pointer to static- hostentstructure containing addresses, aliases, etc. Only reliably handles IPv4. Not thread-safe. Use- getaddrinfo.
- struct hostent *gethostbyaddr(const void *addr, socklen_t len, int type): DEPRECATED. Reverse lookup: find hostname for binary address- addr. Only- AF_INET(- type) usually supported. Returns pointer to static- hostent. Not thread-safe. Use- getnameinfoor- getaddrinfo.
- struct servent *getservbyname(const char *name, const char *proto): DEPRECATED. Look up service- name(e.g., "http") for a given protocol (- proto, e.g., "tcp"). Returns pointer to static- serventstructure containing port number. Not thread-safe. Use- getaddrinfo.
- int getnameinfo(const struct sockaddr *sa, socklen_t salen, char *host, socklen_t hostlen, char *serv, socklen_t servlen, int flags): The modern reverse lookup function. Translate socket address- saback into hostname (stored in- host) and service name (stored in- serv).- flagscontrol lookup behavior (e.g.,- NI_NUMERICHOST,- NI_NUMERICSERVto prevent name resolution,- NI_NAMEREQDto require name). Thread-safe. Returns 0 on success, non-zero- gaierror code on failure.
 
- Provides functions for translating between hostnames/service names and network addresses/port numbers, querying the network databases (like 
          Created
          March 29, 2025 20:31 
        
      - 
      
- 
        Save qpwo/9f577f1ca74f7176687f9e6130bab535 to your computer and use it in GitHub Desktop. 
    top 250 c standard library things
  
        
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment