Professional Documents
Culture Documents
h = fopen("filename", "rb"); size_t fread(void *, size_t, size_t, FILE *); %p printf printf("%p", (void*) ptr)
specifiers
/* error checking missing */ FILE *freopen(char *, char *, FILE *);
while ((ch = fgetc(h)) != EOF) { size_t fwrite(void *, size_t, size_t, FILE *); Specifically a cast to the return value of
malloc() is a definite sign the code author
/* deal with ch */ int ungetc(int, FILE *);
either didn't know what he was doing or
}
didn't choose a good language for the
dynamic memory
/* if needed test why last read failed */ implementation of whatever he's doing.
Remember to #include <stdlib.h>
if (feof(h) || ferror(h)) /* whatever */;
Allocate (BSD) sockets
fclose(h);
malloc ptr = malloc(n * sizeof *ptr); Headers needed
You can replace fgetc(h) with getchar() to
calloc ptr = calloc(n, sizeof *ptr); #include <arpa/inet.h>
read from standard input.
#include <netdb.h>
Change size
#include <string.h>
read file line-by-line realloc newsize = n * sizeof *ptr; tmp =
#include <sys/socket.h>
#include <stdio.h> realloc(ptr, newsize); if (tmp) ptr
#include <unistd.h>
FILE *h; = tmp; else /* ptr is still valid */;
initialize with
char line[100]; Release getaddrinfo()
h = fopen("filename", "rb");
free free(ptr); loop to find and connect a socket
/* error checking missing */
socket()
while (fgets(line, sizeof line, h)) {
remove trailing newline connect()
/* deal with line */
if needed: close()
How do I remove the final newline in a
}
after loop: freeaddrinfo()
string?
/* if needed test why last read failed */
getpeername(), getsockname()
len = strlen(data);
if (feof(h) || ferror(h)) /* whatever */;
send() or recv() or sendto() or recvfrom()
if (len && data[len - 1] == '\n') data[--len] =
fclose(h);
close()
0;
or, if you don't need to keep and update
Flexible Array Member
Predefined C macros
data length
How to declare a FAM?
data[strcspn(data, "\n")] = 0; __FILE__
By using empty brackets as the last
If len is known in advance, do not call "filename.c" or something like that
member of a struct.
strlen(). You can pass the updated len to __LINE__
How to define the size for an object the caller.
42 or another integer
containg a FAM?
ptr = malloc(sizeof *ptr + sizeof (FAMTY‐
PE[wantedsize]));
__STDC__
1
__STDC_VERSION__
undefined for C89; 199901L for C99; 201112L for C11
__DATE__
"Feb 17 2012" for example
__TIME__
"15:16:17" for example
__func__
__STDC_HOSTED__
0 or 1
Reserved identifiers