在学习Linux系统时,除了学习Linux常用命令后,还需要学习Linux API编程。Linux C函数参考手册带书签非常清晰.pdf
LinuxC和WindowsC
文件操作
文件流
fopen
非描述符读写文件
#include <stdio.h>#include <errno.h>#include <string.h>void testCreateFile(){// 1. create fileFILE *fp=fopen( "hello.txt","w+");if(fp==NULL) {printf("fopen err: %s\n",strerror(errno));return;}// 2. write filechar szBuf[100] = {"hello 15pb"};size_t size = fwrite(szBuf, strlen(szBuf), 1, fp);if(size == 0) {printf(" fwrite err");fclose(fp);return;}//移动读写位置到文件尾部,fseek(fp,0,SEEK_END);//获取文件大小int file_size = ftell(fp);//获取完大小再把文件指针移到最开头,不然等下读不到文件fseek(fp,0,SEEK_SET);//read filechar buf[1024]={};int ret = fread(buf,1024,1,fp);//如果file_size这个缓冲区太大了,虽然读进去了,但是返回值为0//如果读取大小超过实际大小,读取成功,但是返回值是0//如果失败,errno的值是非0if(ret==0 && errno!=0){//转换错误消息printf("fread err: %s\n",strerror(errno));}printf("file context: %s\n",buf);// 3. close filefclose(fp) ;}int main(){testCreateFile();}
描述符读写文件
#include <stdio.h>#include <errno.h>#include <string.h>#include <unistd.h>#include <fcntl.h>//测试写方式// 0表示标准输入// 1表示标准输出// 2表示标准错误输出void writefile(){// 1.打开文件//参数1文件名//参数2打开方式//参数3文件权限//返回文件描述符int fd = open("./test.txt", O_CREAT | O_WRONLY, S_IRWXU);if (fd == 0){//转换错误信息printf("open error : %s\n", strerror(errno));return;}//写入文件char buff[] = "hello 15pb\n";//参数1,文件描述符//参数2缓冲区//参数3缓冲区大小write(fd, buff, strlen(buff));//关闭文件close(fd);}void readfile(){int fd = open("./test.txt", O_RDONLY);if (fd == 0){//转换错误信息printf("open error : %s\n", strerror(errno));return;}//读取文件内容char buff[1024] = {};int ret = read(fd,buff,1024);//如果读取大小超过实际大小,读取成功,但是返回值是0//如果失败,errno的值是非0if (ret == 0 && errno != 0){//转换错误消息printf("fread err: %s\n", strerror(errno));}//显示内容printf("file context: %s\n",buff);//关闭文件close(fd);}int main(){//writefile();readfile();return 0;}
通过文件名和文件描述符来获取文件信息
#include <stdio.h>#include <errno.h>#include <string.h>#include <unistd.h>#include <fcntl.h>#include <sys/stat.h>//获取文件信息方式1 .通过文件名void get_file_stat(){struct stat info={};//通过文件名获取文件信息//返回0表示成功,非零表示失败if(0!=stat("./test.txt",&info)){//if括号里边的是会执行的printf("get stat error: %s" ,strerror(errno));return;}//输出文件信息printf("file size %ld \n" ,info.st_size);return ;}//同过描述符获取void get_file_stat2(){int fd = open("./test.txt", O_RDONLY);if (fd == 0){//转换错误信息printf("open error : 8s\n", strerror(errno));return 0;}struct stat info={};//获取文件信息fstat(fd,&info);printf("file size = %ld",info.st_size);close(fd);}int main(){get_file_stat();return 0;}
linuxAPI


#include <dirent.h>#include <stdio.h>#include <errno.h>#include <string.h>//遍历目录void enumdir(char *path){//目录流结构体指针struct DIR *pdir;//打开目录pdir = opendir(path);if (pdir == NULL){//转换错误消息printf("fread err: %s\n", strerror(errno));}struct dirent *info;int number=0;while (info =readdir(pdir)){//输出目录下文件信息printf("file type = %d\n", info->d_type);printf("file name = %s\n", info->d_name);number++;}printf("一共有 %d 个文件",number);//关闭文件closedir(pdir);}int main(){enumdir("/root");return 0;}

