-
<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 tostdout
. Returns number of characters written or negative on error.int fprintf(FILE *stream, const char *format, ...)
: Print formatted string output to the specifiedstream
. 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 stringstr
, writing at mostsize
bytes (including null terminator). Safer alternative tosprintf
. Returns number of characters that would have been written (excluding null) ifsize
was large enough, or negative on error.int sprintf(char *str, const char *format, ...)
: UNSAFE! Print formatted output to the character stringstr
. No bounds checking! Can easily cause buffer overflows. Returns number of characters written (excluding null).int scanf(const char *format, ...)
: Read formatted input fromstdin
. Returns number of items successfully assigned orEOF
.int fscanf(FILE *stream, const char *format, ...)
: Read formatted input from the specifiedstream
. Returns number of items successfully assigned orEOF
.int sscanf(const char *str, const char *format, ...)
: Read formatted input from the character stringstr
. Returns number of items successfully assigned orEOF
.FILE *fopen(const char *pathname, const char *mode)
: Open the file specified bypathname
with the givenmode
(e.g., "r", "w", "a", "rb", "wb", "ab", "+ variants"). ReturnsFILE *
stream orNULL
on error (checkerrno
).int fclose(FILE *stream)
: Close the specified filestream
, flushing any buffered data. Returns 0 on success,EOF
on error.size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
: Readnmemb
items, eachsize
bytes long, fromstream
into the bufferptr
. Used for binary input. Returns number of items successfully read (may be less thannmemb
at EOF or error).size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
: Writenmemb
items, eachsize
bytes long, from bufferptr
tostream
. Used for binary output. Returns number of items successfully written (may be less thannmemb
on error).char *fgets(char *s, int size, FILE *stream)
: Read at mostsize-1
characters fromstream
into the buffers
. Stops on newline (which is included) or EOF. Null-terminatess
. Safer thangets
. Returnss
on success,NULL
on EOF/error.int fputs(const char *s, FILE *stream)
: Write the null-terminated strings
tostream
. Does not write the null terminator or add a newline. Returns non-negative on success,EOF
on error.int puts(const char *s)
: Write the null-terminated strings
and a trailing newline tostdout
. Returns non-negative on success,EOF
on error.int fgetc(FILE *stream)
: Read the next character fromstream
as anunsigned char
cast to anint
. Returns the character orEOF
on end-of-file or error.int getc(FILE *stream)
: Similar tofgetc
, potentially implemented as a macro (beware side effects in arguments).int getchar(void)
: Equivalent togetc(stdin)
. Read next char from standard input.int fputc(int c, FILE *stream)
: Write the characterc
(cast tounsigned char
) tostream
. Returns the character written orEOF
on error.int putc(int c, FILE *stream)
: Similar tofputc
, potentially implemented as a macro.int putchar(int c)
: Equivalent toputc(c, stdout)
. Write charc
to standard output.int fflush(FILE *stream)
: Flush the output buffer of thestream
. Ifstream
isNULL
, flush all output streams. Returns 0 on success,EOF
on error.int fseek(FILE *stream, long offset, int whence)
: Set the file position indicator forstream
.whence
isSEEK_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 forstream
, or -1L on error.void rewind(FILE *stream)
: Equivalent tofseek(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 forstream
is set. Returns non-zero if EOF, 0 otherwise.int ferror(FILE *stream)
: Check if the error indicator forstream
is set. Returns non-zero if error, 0 otherwise.void clearerr(FILE *stream)
: Clear the end-of-file and error indicators forstream
.void perror(const char *s)
: Print the strings
, a colon, a space, and the system error message corresponding to the currenterrno
value tostderr
.int remove(const char *pathname)
: Delete the file specified bypathname
. Returns 0 on success, non-zero on error.int rename(const char *oldpath, const char *newpath)
: Rename/move the fileoldpath
tonewpath
. Returns 0 on success, non-zero on error.char *gets(char *s)
: UNSAFE! EXTREMELY DANGEROUS! Reads a line from stdin intos
without 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
) forstream
. 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. Usemkstemp
instead.FILE *tmpfile(void)
: Creates and opens a unique temporary binary file ("wb+") that is automatically removed when closed or program terminates. ReturnsFILE*
orNULL
. Safer thantmpnam
.
- 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)
: Allocatesize
bytes of raw, uninitialized memory block dynamically on the heap; returns pointer to allocated memory orNULL
on failure.void free(void *ptr)
: Deallocate the memory block pointed to byptr
(which must have been returned bymalloc
,calloc
, orrealloc
, or beNULL
). PassingNULL
is safe and does nothing.void *calloc(size_t nmemb, size_t size)
: Allocate memory for an array ofnmemb
elements ofsize
bytes each, initialize allocated memory to zero; returns pointer orNULL
on failure.void *realloc(void *ptr, size_t size)
: Change the size of the previously allocated memory block atptr
tosize
bytes. May move the block. Returns new pointer orNULL
on failure. Ifptr
isNULL
, equivalent tomalloc(size)
. Ifsize
is 0, may freeptr
or return unique pointer (behavior varies, best to usefree
explicitly).void exit(int status)
: Terminate the calling process normally. Performs cleanup (flushes stdio, callsatexit
handlers) then calls_exit(status)
.status
is exit code (0 orEXIT_SUCCESS
for success,EXIT_FAILURE
or non-zero for failure).void abort(void)
: Cause abnormal process termination (often by raisingSIGABRT
). May not perform standard cleanup.int atexit(void (*func)(void))
: Register a functionfunc
to be called automatically at normal program termination (exit()
or return frommain
). Returns 0 on success.long strtol(const char *nptr, char **endptr, int base)
: Convert the initial part of the stringnptr
to along int
value according to the givenbase
(0, 2-36). Stores pointer to first invalid char in*endptr
(if notNULL
). Robust error checking viaerrno
andendptr
.unsigned long strtoul(const char *nptr, char **endptr, int base)
: Convert the initial part of the stringnptr
to anunsigned long int
. Similar robustness tostrtol
.double strtod(const char *nptr, char **endptr)
: Convert the initial part of the stringnptr
to adouble
. Similar robustness. Robust error checking viaerrno
andendptr
.int rand(void)
: Return a pseudo-random integer between 0 andRAND_MAX
. Low quality PRNG, not suitable for cryptography or serious simulations.void srand(unsigned int seed)
: Seed the pseudo-random number generator used byrand()
withseed
. Often seeded withtime(NULL)
.void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *))
: Sort an arraybase
ofnmemb
elements each ofsize
bytes, using thecompar
function for comparison.compar(a, b)
should return <0 ifa<b
, 0 ifa==b
, >0 ifa>b
.void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *))
: Perform binary search forkey
in the sorted arraybase
. Returns pointer to matching element orNULL
if not found.compar
function same as forqsort
.char *getenv(const char *name)
: Get the value of an environment variablename
. Returns pointer to value string (do not modify) orNULL
if not found.int system(const char *command)
: Execute a shellcommand
. Returns command's exit status or -1 on error. Warning: Security risks ifcommand
string contains untrusted user input (potential command injection). Ifcommand
isNULL
, returns non-zero if shell is available, 0 otherwise.int abs(int j)
: Compute absolute value of integerj
. (Behavior undefined forINT_MIN
).long labs(long j)
: Compute absolute value of long integerj
. (Behavior undefined forLONG_MIN
).div_t div(int numerator, int denominator)
: Compute integer divisionnumerator / denominator
. Returnsdiv_t
struct containingquot
(quotient) andrem
(remainder). Handles signs correctly.ldiv_t ldiv(long numerator, long denominator)
: Long integer version ofdiv
. Returnsldiv_t
struct.int atoi(const char *nptr)
: UNSAFE (limited)! Convert initial part of stringnptr
toint
. No error checking (returns 0 on error, indistinguishable from valid 0). Usestrtol
for robustness.long atol(const char *nptr)
: UNSAFE (limited)! Convert initial part of stringnptr
tolong
. No error checking. Usestrtol
.double atof(const char *nptr)
: UNSAFE (limited)! Convert initial part of stringnptr
todouble
. Limited error checking. Usestrtod
for robustness.char *mktemp(char *template)
: UNSAFE! Creates a unique temporary filename based ontemplate
(which must end in XXXXXX). Modifiestemplate
. Prone to race conditions. Usemkstemp
. Removed in POSIX.1-2008.int mkstemp(char *template)
: (Requires<unistd.h>
typically, but closely related tomktemp
). Creates and opens a unique temporary file based ontemplate
(ending in XXXXXX), modifyingtemplate
to the actual filename. Returns file descriptor. Much safer thanmktemp
.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 byrand()
.
-
<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)
: Copyn
bytes from memory areasrc
to memory areadest
. Behavior is undefined ifsrc
anddest
overlap. Returnsdest
.void *memmove(void *dest, const void *src, size_t n)
: Copyn
bytes from memory areasrc
to memory areadest
. Areas may overlap (handles overlap correctly). Returnsdest
.void *memset(void *s, int c, size_t n)
: Fill the firstn
bytes of the memory areas
with the constant bytec
(converted tounsigned char
). Returnss
. Often used to zero memory (e.g.,memset(ptr, 0, size)
).int memcmp(const void *s1, const void *s2, size_t n)
: Compare the firstn
bytes of memory areass1
ands2
. Returns an integer less than, equal to, or greater than zero ifs1
is found, respectively, to be less than, to match, or be greater thans2
.void *memchr(const void *s, int c, size_t n)
: Scan the firstn
bytes of memory areas
for the first instance of bytec
(converted tounsigned char
). Returns pointer to the byte orNULL
if not found.size_t strlen(const char *s)
: Calculate the length of the null-terminated strings
(excluding the null byte).char *strcpy(char *dest, const char *src)
: UNSAFE! Copy the null-terminated stringsrc
todest
(including null terminator). No bounds checking! High risk of buffer overflows. Usestrncpy
(carefully) orsnprintf
. Returnsdest
.char *strncpy(char *dest, const char *src, size_t n)
: Copy at mostn
bytes from stringsrc
todest
. Warning: Ifstrlen(src) >= n
,dest
will not be null-terminated. Always ensure null termination manually if needed (e.g.,dest[n-1] = '\0';
ifn > 0
). Returnsdest
.char *strcat(char *dest, const char *src)
: UNSAFE! Append the null-terminated stringsrc
to the end ofdest
. No bounds checking ondest
! High risk of buffer overflows. Usestrncat
. Returnsdest
.char *strncat(char *dest, const char *src, size_t n)
: Append at mostn
bytes from stringsrc
todest
, plus a null terminator. Safer thanstrcat
, but requiresdest
to have enough space for its original content,n
bytes fromsrc
, and the null terminator. Always null-terminates (unlikestrncpy
). Returnsdest
.int strcmp(const char *s1, const char *s2)
: Compare two null-terminated stringss1
ands2
lexicographically. Returns <0, 0, or >0.int strncmp(const char *s1, const char *s2, size_t n)
: Compare at mostn
bytes (or until a null terminator) of stringss1
ands2
. Returns <0, 0, or >0.char *strchr(const char *s, int c)
: Find the first occurrence of the characterc
(converted tochar
) in the null-terminated strings
. Returns pointer to the character ins
orNULL
if not found.char *strrchr(const char *s, int c)
: Find the last occurrence of the characterc
(converted tochar
) in the null-terminated strings
. Returns pointer orNULL
.char *strstr(const char *haystack, const char *needle)
: Find the first occurrence of the null-terminated substringneedle
within the null-terminated stringhaystack
. Returns pointer to the beginning of the substring inhaystack
orNULL
.size_t strspn(const char *s, const char *accept)
: Calculate the length of the initial segment ofs
which consists only of characters found inaccept
.size_t strcspn(const char *s, const char *reject)
: Calculate the length of the initial segment ofs
which consists only of characters not found inreject
.char *strpbrk(const char *s, const char *accept)
: Find the first character ins
that matches any character specified inaccept
. Returns pointer to the character orNULL
.char *strtok(char *str, const char *delim)
: UNSAFE (Stateful/Not Reentrant)! Find tokens (substrings separated bydelim
) instr
. Modifiesstr
by inserting null bytes. Passstr
on first call,NULL
on subsequent calls to get next token. Not thread-safe. Usestrtok_r
(POSIX) if available. Returns pointer to token orNULL
.char *strerror(int errnum)
: Return a pointer to a string describing the error codeerrnum
. The string may be statically allocated and overwritten by subsequent calls (potentially not thread-safe depending on implementation). Usestrerror_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 bysizeof
operator, 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 amember
within astruct
orunion
oftype
. Result is of typesize_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 avoid*
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 forsize_t
.
-
<errno.h>
(System Error Numbers)- Defines the integer variable
errno
and 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
errno
value 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 likeread
,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 tocount
bytes from file descriptorfd
intobuf
. Returns bytes read (0 on EOF), or -1 on error (checkerrno
).int write(int fd, const void *buf, size_t count)
: Write up tocount
bytes frombuf
to file descriptorfd
. Returns bytes written, or -1 on error (checkerrno
).int close(int fd)
: Close the file descriptorfd
. 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 descriptorfd
.whence
isSEEK_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 frompathname
.argv
is the argument list (null-terminated array),envp
is the environment (null-terminated array). Does not return on success. Returns -1 on error. The coreexec
function.int execv(const char *pathname, char *const argv[])
: Likeexecve
, uses current environment.int execvp(const char *file, char *const argv[])
: Likeexecv
, but searchesPATH
environment variable forfile
if it doesn't contain a slash. Common variant.int execl(const char *pathname, const char *arg, ... /*, (char *) NULL */)
: List-based variant ofexec
, takes arguments as separateconst char*
parameters, terminated byNULL
. Uses current environment.int execlp(const char *file, const char *arg, ... /*, (char *) NULL */)
: List-based variant likeexecl
, but searchesPATH
likeexecvp
.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.status
is exit code (low 8 bits available to parent viawait
). Usually called byexit()
.unsigned int alarm(unsigned int seconds)
: Arrange forSIGALRM
signal to be delivered to the process inseconds
. Ifseconds
is 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 witherrno
set toEINTR
.unsigned int sleep(unsigned int seconds)
: Suspend execution for the specified number ofseconds
, 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 forusec
microseconds. Usenanosleep
instead. 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 descriptoroldfd
, returning the lowest unused non-negative descriptor. Returns new fd or -1.int dup2(int oldfd, int newfd)
: Duplicateoldfd
tonewfd
, closingnewfd
first if necessary. Ifoldfd
==newfd
, does nothing. Returnsnewfd
or -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 topath
. Returns 0 on success, -1 on error.char *getcwd(char *buf, size_t size)
: Copy the absolute pathname of the current working directory tobuf
(up tosize
bytes). Ifbuf
isNULL
, allocates buffer (needsfree
). Returnsbuf
orNULL
on error.char *getwd(char *buf)
: UNSAFE! DEPRECATED! Get current working directory intobuf
. Cannot specify buffer size, potential overflow. Usegetcwd
.int chown(const char *pathname, uid_t owner, gid_t group)
: Change the owner and group of a file specified bypathname
. Use -1 for owner/group to leave unchanged. Returns 0 on success, -1 on error. (lchown
changes symlink itself,fchown
uses fd).int access(const char *pathname, int mode)
: Check user's permissions for a file.mode
is bitwise OR ofR_OK
,W_OK
,X_OK
(test permissions), orF_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 descriptorfd
refers to a terminal. Returns 1 if it is, 0 otherwise (settingerrno
if error occurs).int link(const char *oldpath, const char *newpath)
: Create a new hard linknewpath
for the existing fileoldpath
. Returns 0 on success, -1 on error.int symlink(const char *target, const char *linkpath)
: Create a symbolic link namedlinkpath
containing the stringtarget
. Returns 0 on success, -1 on error.ssize_t readlink(const char *pathname, char *buf, size_t bufsiz)
: Read the value of a symbolic linkpathname
intobuf
(up tobufsiz
bytes). Does not null-terminatebuf
. 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
).flags
is 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.). Optionalmode
argument (e.g.,0644
) is required only whenO_CREAT
is specified, sets initial permissions (modified by umask). Returns fd or -1 on error.int creat(const char *pathname, mode_t mode)
: DEPRECATED. Equivalent toopen(pathname, O_WRONLY|O_CREAT|O_TRUNC, mode)
. Useopen
directly.int fcntl(int fd, int cmd, ... /* arg */)
: Perform various operations (cmd
) on file descriptorfd
. Common commands:F_DUPFD
: Duplicate fd (likedup
, but to lowest >=arg
).F_GETFD
/F_SETFD
: Get/set fd flags (e.g.,FD_CLOEXEC
).arg
is int.F_GETFL
/F_SETFL
: Get/set file status flags (e.g.,O_APPEND
,O_NONBLOCK
).arg
is int.F_GETLK
/F_SETLK
/F_SETLKW
: Get/Set/Set-and-wait for file locks.arg
isstruct flock *
.
- Common
open
/fcntl
flags: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 withO_CREAT
, ensuresopen
fails 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 withEAGAIN
/EWOULDBLOCK
).O_CLOEXEC
: Set the close-on-exec flag for the new file descriptor (atomically). Prevents fd leakage acrossexec
.
FD_CLOEXEC
: File descriptor flag (forF_GETFD
/F_SETFD
) indicating fd should be closed automatically uponexec
.
- Defines functions and constants for manipulating file descriptors, such as opening files (
-
<sys/stat.h>
(File Status and Information)- Defines the
stat
structure 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 forpathname
(follows symbolic links) and store it instatbuf
. Returns 0 on success, -1 on error.int fstat(int fd, struct stat *statbuf)
: Get file status for the open file descriptorfd
. Returns 0 on success, -1 on error.int lstat(const char *pathname, struct stat *statbuf)
: Get file status forpathname
. Ifpathname
is 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 namedpathname
with specified initialmode
(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 filepathname
. Returns 0 on success, -1 on error. (fchmod
operates on an fd).mode_t umask(mode_t mask)
: Set the process's file mode creation mask and return the previous mask. Bits set inmask
are cleared from the mode specified inopen
ormkdir
.- File type macros (for testing
st_mode
field):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? (Uselstat
to get mode for link itself).S_ISSOCK(m)
: Is it a socket?
- Permission bits (for
st_mode
field andmode
arguments 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 bylseek
).mode_t
: Integer type for file modes/permissions (used bystat
,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 withsigaction
to 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 signalsignum
.act
specifies 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 signalsignum
.handler
can beSIG_DFL
(default),SIG_IGN
(ignore), or a function pointer. Semantics vary across systems (especially regarding handler re-installation). Usesigaction
instead for reliable behavior. Returns previous handler orSIG_ERR
on error.int kill(pid_t pid, int sig)
: Send signalsig
to processpid
. Specialpid
values: >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 signalsig
to the calling process or thread. Equivalent tokill(getpid(), sig)
. Returns 0 on success, non-zero on error.int sigemptyset(sigset_t *set)
: Initialize the signal setset
to be empty (exclude all signals). Returns 0 on success, -1 on error.int sigfillset(sigset_t *set)
: Initialize the signal setset
to be full (include all signals). Returns 0 on success, -1 on error.int sigaddset(sigset_t *set, int signum)
: Add signalsignum
to the signal setset
. Returns 0 on success, -1 on error.int sigdelset(sigset_t *set, int signum)
: Remove signalsignum
from the signal setset
. Returns 0 on success, -1 on error.int sigismember(const sigset_t *set, int signum)
: Test ifsignum
is a member of the signal setset
. 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
(addset
to mask),SIG_UNBLOCK
(removeset
from mask),SIG_SETMASK
(set mask toset
). Ifoldset
is 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 inset
. Returns 0 on success, -1 on error.int sigsuspend(const sigset_t *mask)
: Atomically set the signal mask tomask
and suspend the process until a signal is caught (whose action isn't ignore) or terminates the process. Restores original mask on return. Returns -1 witherrno
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 fromsignal
indicating 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., fromabort()
).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 fromalarm()
.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. Ifwstatus
is notNULL
, stores status information there. Returns PID of the child whose state changed, or -1 on error (e.g., no children). Equivalent towaitpid(-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 PIDpid
.pid == -1
: Wait for any child process (likewait
).pid == 0
: Wait for any child in the calling process's process group.pid < -1
: Wait for any child in the process groupabs(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
WNOHANG
and no change), or -1 on error.
- Wait status analysis macros (used with the
wstatus
value):WIFEXITED(wstatus)
: Returns true (non-zero) if the child terminated normally (viaexit()
orreturn
frommain
).WEXITSTATUS(wstatus)
: IfWIFEXITED
is 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)
: IfWIFSIGNALED
is true, returns the number of the signal that terminated the child.WIFSTOPPED(wstatus)
: Returns true if the child was stopped by a signal (requiresWUNTRACED
orWCONTINUED
inwaitpid
).WSTOPSIG(wstatus)
: IfWIFSTOPPED
is true, returns the number of the signal that stopped the child.WIFCONTINUED(wstatus)
: Returns true if the child was resumed bySIGCONT
(requiresWCONTINUED
).
-
<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 astime_t
(seconds since the Epoch). Iftloc
is notNULL
, the value is also stored there. Returns current time or(time_t)-1
on error.struct tm *localtime(const time_t *timep)
: Converttime_t
valuetimep
into broken-down timestruct tm
expressed in the system's local timezone. Warning: Returns pointer to a static internal buffer, which may be overwritten by subsequent calls tolocaltime
orgmtime
. Not thread-safe. Uselocaltime_r
(POSIX) for thread-safety.struct tm *gmtime(const time_t *timep)
: Converttime_t
valuetimep
into broken-down timestruct tm
expressed in Coordinated Universal Time (UTC, often called GMT). Warning: Returns pointer to static data, not thread-safe. Usegmtime_r
(POSIX).time_t mktime(struct tm *tm)
: Convert broken-down local timestruct tm
(fieldstm_wday
andtm_yday
are ignored, others normalized) intotime_t
calendar time value. Returnstime_t
value or(time_t)-1
if it cannot be represented. Modifies thetm
struct, filling intm_wday
andtm_yday
.size_t strftime(char *s, size_t maxsize, const char *format, const struct tm *tm)
: Format the broken-down timetm
into the strings
(up tomaxsize
bytes, including null) according toformat
specifiers (e.g.,%Y
year,%m
month,%d
day,%H
hour,%M
min,%S
sec,%Z
timezone name). Returns number of bytes written (excluding null) or 0 ifmaxsize
was too small.char *asctime(const struct tm *tm)
: Convertstruct tm
into a standard C string format (e.g., "Wed Jun 30 21:49:08 1993\n"). Warning: Returns pointer to static data, not thread-safe. Usestrftime
.char *ctime(const time_t *timep)
: Converttime_t
into a standard C string format (likeasctime
). Equivalent toasctime(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 twotime_t
values (time1
-time0
), returned as adouble
.clock_t clock(void)
: Return the processor time consumed by the program since invocation, measured inclock_t
units. Divide byCLOCKS_PER_SEC
to get seconds. May wrap. Quality/granularity varies.CLOCKS_PER_SEC
: Macro defining the number ofclock_t
ticks 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 withgettimeofday
for timezone information. Do not use; passNULL
for thetz
argument.int gettimeofday(struct timeval *tv, struct timezone *tz)
: Get the current time as seconds and microseconds since the Epoch.tz
argument is obsolete and should beNULL
. Returns 0 on success, -1 on error. Still very common, though POSIX favorsclock_gettime
from<time.h>
(if available withCLOCK_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
double
floating-point numbers. double sqrt(double x)
: Compute the non-negative square root ofx
(x >= 0
).double pow(double base, double exp)
: Computebase
raised to the powerexp
(base^exp
). Handles various edge cases (0, infinity, NaN).double fabs(double x)
: Compute the absolute value of floating-point numberx
. (fabsf
forfloat
,fabsl
forlong double
).double fmod(double x, double y)
: Compute floating-point remainder ofx/y
. Result has the same sign asx
.double exp(double x)
: Compute e (Euler's number, ~2.718) raised to the powerx
(e^x
).double log(double x)
: Compute the natural logarithm (base e) ofx
(x > 0
).double log10(double x)
: Compute the base-10 logarithm ofx
(x > 0
).double sin(double x)
,double cos(double x)
,double tan(double x)
: Compute sine, cosine, tangent ofx
(wherex
is in radians).double asin(double x)
,double acos(double x)
,double atan(double x)
: Compute arc sine (x
in [-1,1]), arc cosine (x
in [-1,1]), arc tangent ofx
. Results are in radians.double atan2(double y, double x)
: Compute arc tangent ofy/x
, using the signs ofx
andy
to determine the correct quadrant for the result (in radians, range [-pi, pi]).double ceil(double x)
: Roundx
upward to the nearest integer value (returned asdouble
). "Ceiling".double floor(double x)
: Roundx
downward to the nearest integer value (returned asdouble
). "Floor".double round(double x)
: (C99) Roundx
to the nearest integer value (returned asdouble
), rounding halfway cases away from zero.double trunc(double x)
: (C99) Roundx
toward zero to the nearest integer value (returned asdouble
).double hypot(double x, double y)
: (C99) Computesqrt(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 (float
type).NAN
: (C99) Macro representing a "Not a Number" floating-point value (float
type).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
int
argument but typically operate on values representable asunsigned char
orEOF
. int isalnum(int c)
: Check ifc
is alphanumeric (isalpha
orisdigit
).int isalpha(int c)
: Check ifc
is an alphabetic character (isupper
orislower
).int iscntrl(int c)
: Check ifc
is a control character.int isdigit(int c)
: Check ifc
is a decimal digit ('0'-'9').int isgraph(int c)
: Check ifc
is any printable character except space.int islower(int c)
: Check ifc
is a lowercase letter.int isprint(int c)
: Check ifc
is a printable character (including space).int ispunct(int c)
: Check ifc
is a punctuation character (printable, not space orisalnum
).int isspace(int c)
: Check ifc
is whitespace (space ' ', form feed '\f', newline '\n', carriage return '\r', horizontal tab '\t', vertical tab '\v').int isupper(int c)
: Check ifc
is an uppercase letter.int isxdigit(int c)
: Check ifc
is a hexadecimal digit ('0'-'9', 'a'-'f', 'A'-'F').int tolower(int c)
: Convert uppercase letterc
to lowercase. Returnsc
unchanged if not uppercase.int toupper(int c)
: Convert lowercase letterc
to uppercase. Returnsc
unchanged 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
true
andfalse
for improved code clarity. Often implemented via macros that expand to integer types/values. bool
: Macro expanding to the boolean type (_Bool
typically).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 achar
.CHAR_MIN
,CHAR_MAX
: Minimum/Maximum value forchar
.SCHAR_MIN
,SCHAR_MAX
: Minimum/Maximum value forsigned char
.UCHAR_MAX
: Maximum value forunsigned char
.SHRT_MIN
,SHRT_MAX
: Minimum/Maximum value forshort int
.USHRT_MAX
: Maximum value forunsigned short int
.INT_MIN
,INT_MAX
: Minimum/Maximum value forint
.UINT_MAX
: Maximum value forunsigned int
.LONG_MIN
,LONG_MAX
: Minimum/Maximum value forlong int
.ULONG_MAX
: Maximum value forunsigned long int
.LLONG_MIN
,LLONG_MAX
: (C99) Minimum/Maximum value forlong long int
.ULLONG_MAX
: (C99) Maximum value forunsigned 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
assert
macro, used for inserting run-time sanity checks during development. void assert(scalar expression)
: If the macroNDEBUG
is not defined at the point of inclusion of<assert.h>
,assert
evaluatesexpression
. Ifexpression
is false (evaluates to 0),assert
prints an error message (including the expression text, file name, and line number) tostderr
and then callsabort()
. IfNDEBUG
is defined, theassert
macro 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
printf
orscanf
). va_list
: Type suitable for holding information needed byva_start
,va_arg
, andva_end
.void va_start(va_list ap, last)
: Initializesap
for use byva_arg
andva_end
.last
must be the name of the last fixed parameter before the variable arguments (...
). Must be called before firstva_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.ap
must have been initialized byva_start
.type
is the expected type of the next argument. Behavior undefined if no next argument or iftype
is incompatible. Modifiesap
.void va_end(va_list ap)
: Performs necessary cleanup forap
after all arguments have been processed. Must be called before the function returns ifva_start
was called.void va_copy(va_list dest, va_list src)
: (C99) Creates a copydest
of the current variable argument list statesrc
. Useful if the list needs to be scanned more than once.dest
must also be passed tova_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_INET
for IPv4,AF_INET6
for IPv6,AF_UNIX
for local).type
: Communication semantics (e.g.,SOCK_STREAM
for reliable stream/TCP,SOCK_DGRAM
for datagram/UDP,SOCK_RAW
for raw network protocol access). AddSOCK_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 socketsockfd
. Typically used on the server side beforelisten
or for specific client-side source address/port. Returns 0 on success, -1 on error.int listen(int sockfd, int backlog)
: Marksockfd
(which must be of typeSOCK_STREAM
orSOCK_SEQPACKET
) as a passive socket that will be used to accept incoming connection requests.backlog
suggests 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 socketsockfd
, extract the first connection request on the queue, create a new connected socket for this specific connection, and return its file descriptor. Ifaddr
andaddrlen
are non-NULL, they are filled with the address of the connecting peer (client).addrlen
is value-result: initialize it tosizeof(*addr)
before the call. Blocks by default until a connection arrives. Returns new socket fd or -1 on error. (Linux extension:accept4
adds flags likeSOCK_NONBLOCK
,SOCK_CLOEXEC
).int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen)
: Initiate a connection on socketsockfd
(client side) to the server address specified byaddr
. 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)
: Sendlen
bytes frombuf
on a connected socketsockfd
.flags
modify behavior (e.g.,MSG_NOSIGNAL
on Linux preventsSIGPIPE
). Returns number of bytes sent (can be less thanlen
) or -1 on error.ssize_t recv(int sockfd, void *buf, size_t len, int flags)
: Receive up tolen
bytes intobuf
from a connected socketsockfd
.flags
modify behavior (e.g.,MSG_PEEK
looks 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)
: Sendlen
bytes frombuf
on socketsockfd
(can be connected or unconnected, typically UDP) to the specific destination addressdest_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 tolen
bytes intobuf
from socketsockfd
. Ifsrc_addr
andaddrlen
are non-NULL, they are filled with the address of the sender.addrlen
is 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 socketsockfd
.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 socketsockfd
.level
indicates protocol level (e.g.,SOL_SOCKET
,IPPROTO_TCP
).optname
is the option name (e.g.,SO_REUSEADDR
,SO_ERROR
,TCP_NODELAY
). Value stored inoptval
, length inoptlen
(value-result). Returns 0 or -1.int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen)
: Set options for socketsockfd
. Parameters similar togetsockopt
. Returns 0 or -1.struct sockaddr
: Generic socket address structure (base type, containssa_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 foraccept
orrecvfrom
. Containsss_family
.socklen_t
: Unsigned integer type used for socket address structure lengths (passed tobind
,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 (
optname
forSOL_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 tosockfd
.int getpeername(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
: Get the remote address/port connected tosockfd
.
-
<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
socket
protocol
field orgetprotobyname
):IPPROTO_IP
,IPPROTO_TCP
,IPPROTO_UDP
,IPPROTO_IPV6
,IPPROTO_ICMP
. INADDR_ANY
: IPv4 wildcard address (0.0.0.0) for binding (usehtonl(INADDR_ANY)
).INADDR_LOOPBACK
: IPv4 loopback address (127.0.0.1) (usehtonl(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 stringsrc
(e.g., "192.0.2.1" or "2001:db8::1") in presentation format to binary network address format (stored indst
, which should be astruct in_addr *
forAF_INET
orstruct in6_addr *
forAF_INET6
).af
specifies the address family. Modern, preferred, thread-safe, handles IPv4/IPv6. Returns 1 on success, 0 ifsrc
is not a valid address string foraf
, -1 on error (errno
set).const char *inet_ntop(int af, const void *src, char *dst, socklen_t size)
: Convert binary network addresssrc
(struct in_addr *
orstruct in6_addr *
) to presentation format stringdst
.size
is the size of thedst
buffer. Modern, preferred, thread-safe, handles IPv4/IPv6. Returns pointer todst
on success,NULL
on error (errno
set, e.g.,ENOSPC
ifsize
too small). UseINET_ADDRSTRLEN
andINET6_ADDRSTRLEN
(defined in<netinet/in.h>
) for adequate buffer sizes.in_addr_t inet_addr(const char *cp)
: DEPRECATED/UNSAFE! Convert IPv4 address stringcp
(dotted-decimal) to binaryuint32_t
in network byte order. ReturnsINADDR_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. Useinet_pton
.char *inet_ntoa(struct in_addr in)
: DEPRECATED/UNSAFE! Convert binary IPv4 addressin
(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. Useinet_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 bygetaddrinfo
to 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 ofai_addr
.struct sockaddr *ai_addr
: Pointer to socket address structure.char *ai_canonname
: Pointer to canonical hostname (ifAI_CANONNAME
requested).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 moreaddrinfo
structures, returned as a linked list viares
.hints
provides 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 tosocket
,bind
,connect
. Returns 0 on success, non-zero error code (usegai_strerror
to convert to string) on failure.void freeaddrinfo(struct addrinfo *res)
: Free the linked list ofaddrinfo
structures allocated and returned bygetaddrinfo
. Must be called to prevent memory leaks.const char *gai_strerror(int errcode)
: Convert the error code returned bygetaddrinfo
into a human-readable string.struct hostent *gethostbyname(const char *name)
: DEPRECATED. Look up hostname
(hostname or IPv4 dotted-decimal). Returns pointer to statichostent
structure containing addresses, aliases, etc. Only reliably handles IPv4. Not thread-safe. Usegetaddrinfo
.struct hostent *gethostbyaddr(const void *addr, socklen_t len, int type)
: DEPRECATED. Reverse lookup: find hostname for binary addressaddr
. OnlyAF_INET
(type
) usually supported. Returns pointer to statichostent
. Not thread-safe. Usegetnameinfo
orgetaddrinfo
.struct servent *getservbyname(const char *name, const char *proto)
: DEPRECATED. Look up servicename
(e.g., "http") for a given protocol (proto
, e.g., "tcp"). Returns pointer to staticservent
structure containing port number. Not thread-safe. Usegetaddrinfo
.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 addresssa
back into hostname (stored inhost
) and service name (stored inserv
).flags
control lookup behavior (e.g.,NI_NUMERICHOST
,NI_NUMERICSERV
to prevent name resolution,NI_NAMEREQD
to require name). Thread-safe. Returns 0 on success, non-zerogai
error 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