3-b.c
来自「Linux下的C代码 实现了对Linux的文件系统的操作」· C语言 代码 · 共 59 行
C
59 行
#include <fcntl.h> /* including open() */#include <sys/stat.h> /* including S_IRUSR... */#include <stdio.h>#include <stdlib.h> /* including exit() */#include <unistd.h> /* including write, close() */#include <string.h>void err_quit(char* msg);int main(int argc, char** argv){ int i, len; int fd; char temp[5] = {0, }; char *buffer; if ((buffer = (char*)malloc(1024)) == NULL) err_quit("malloc error"); memset(buffer, 0, 1024); if ((fd = open("tempfile", O_RDWR | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) err_quit("open error"); for (i=1; i<=100; i++) sprintf(buffer+strlen(buffer), "%d", i); len = strlen(buffer); if (write(fd, buffer, len) != len) err_quit("write error\n"); if (lseek(fd, 50, SEEK_SET) < 0) err_quit("lseek error\n"); if (read(fd, temp, 1) != 1) err_quit("read error"); printf("The 50th byte is: %s\n", temp); if (lseek(fd, 100, SEEK_SET) < 0 ) err_quit("lseek error\n"); if (read(fd, temp, 1) != 1) err_quit("read error"); printf("The 100th byte is: %s\n", temp); close(fd); if (unlink("tempfile") < 0) err_quit("unlink error"); return 0; }void err_quit(char* msg){ fprintf(stderr, msg); exit(1);}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?