打印当前机器是小头派还是大头派类型
注意,如果没有加这两个头文件
#include <stdio.h>
#include <stdlib.h>
编译时候会报 警告:隐式声明与内建函数‘printf’不兼容 这个错误
编译: gcc -o byteorder byteorder.c
#include <stdio.h> #include <stdlib.h> int main(int argc,char **argv) { union { short s; char c[sizeof(short)]; }un; un.s=0x0102; if(sizeof(short) ==2) { if(un.c[0]==1 && un.c[1]==2) { printf("big-endian\n"); } else if(un.c[0]==2 && un.c[1]==1) { printf("little-endian\n"); } else { printf("unknown\n"); } } else { printf("sizeof(short) = %d\n",sizeof(short)); } return 0; }
10进制ip到二进制转换的例子
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> int main (void) { char IPdotdec[20]; //存放点分十进制IP地址 struct in_addr s; // IPv4地址结构体 // 输入IP地址 printf("Please input IP address: "); scanf("%s", IPdotdec); // // 转换 inet_pton(AF_INET, IPdotdec, (void *)&s); printf("inet_pton: 0x%x\n", s.s_addr); // 注意得到的字节序 // 反转换 inet_ntop(AF_INET, (void *)&s, IPdotdec, 16); printf("inet_ntop: %s\n", IPdotdec); }
一次读取n个字节的readn函数
#include <stdio.h> #include <stdlib.h> #include <netinet/in.h> #include <unistd.h> #include <fcntl.h> ssize_t readn(int fd,void *vptr, size_t n) { size_t nleft; ssize_t nread; char *ptr; ptr = vptr; nleft = n; while(nleft > 0) { if( (nread=read(fd,ptr,nleft)) < 0) { if(nread > 0) { nread = 0; } else { return -1; } } else if(nread == 0) { break; } nleft -= nread; ptr += nread; } return (n-nleft); } int main(int argc, char **argv) { int r_fd=open("/data0/test/test.log",O_RDONLY); char buf[100]; readn(r_fd,buf,20); printf("%s\n",buf); return 0; }
一次写入n个字节的writen函数
#include <stdio.h> #include <stdlib.h> #include <netinet/in.h> #include <unistd.h> #include <fcntl.h> ssize_t writen(int fd, const void *vptr, size_t n) { size_t nleft; ssize_t nwritten; const char *ptr; ptr = vptr; nleft = n; while(nleft > 0) { if( (nwritten = write(fd,ptr,nleft)) <= 0) { if(nwritten <0) { nwritten = 0; } else { return -1; } } nleft -= nwritten; ptr += nwritten; } return n; } int main(int argc, char **argv) { int w_fd = open("/data0/test/write.log",O_WRONLY|O_CREAT,0755); writen(w_fd,"test he he",10); return 0; }
每次读取一行的readline函数
#include <stdio.h> #include <stdlib.h> #include <netinet/in.h> #include <unistd.h> #include <fcntl.h> ssize_t readline(int fd, void *vptr, size_t maxlen) { ssize_t n,rc; char c, *ptr; ptr = vptr; for(n=1;n<maxlen;n++) { if( (rc=read(fd,&c,1)) ==1) { *ptr++ = c; if(c=='\n') { break; } } else if(rc == 0) { *ptr = 0; return (n-1); } else { if(rc < 0) { continue; } return -1; } } *ptr = 0; return n; } int main(int argc, char **argv) { int r_fd=open("/data0/test/test.log",O_RDONLY); char buf[100]; readline(r_fd,buf,20); printf("%s\n",buf); return 0; }
参考
inet_pton函数