系统调用:所有的操作系统都提供多种服务的入口点,程序由此向内核请求服务。这些可直接进入内核的入口点被称为系统调用。
不同操作系统提供了自己的一套系统调用,所以系统调用无法实现跨平台使用。而且频繁地系统调用,在用户态和内核态之间切换,很耗费资源,效率不高。C标准库提供了操作文件的标准I/O函数库,与系统调用相比,主要差别是实现了一个跨平台的用户态缓冲的解决方案。缓冲区可以减少系统调用的次数,提高运行效率。C标准库是系统调用的封装,在内部区分了操作系统,可实现跨平台使用。
1、打开和关闭文件:
系统调用函数:
函数原型:
int open(const char *pathname, int flags); int open(const char *pathname, int flags, mode_t mode); int creat(const char *pathname, mode_t mode); int close(int fd);代码示例:
int fd; if (fd = open("test.txt",O_RDONLY | O_CREAT,O_IWOTH) == -1) { printf ("文件打开失败\n"); perror ("open"); } close(fd);标准I/O函数:
函数原型:
FILE *fopen(const char *path, const char *mode); FILE *fdopen(int fildes, const char *mode); FILE *freopen(const char *path, const char *mode, FILE *stream); int fclose(FILE *fp);代码示例:
FILE *fp = fopen("abc","a"); if(fp == NULL) { perror("fopen"); return -1; } printf ("文件打开成功\n"); fclose (fp);2、读文件和写文件:
系统调用函数:
函数原型:
ssize_t read(int fd, void *buf, size_t count); ssize_t write(int fd, const void *buf, size_t count);代码示例(复制文件):
int fd1 = open("1.ppt",O_RDONLY); if (fd1 == -1) { perror("open"); } int fd2 = open("2.ppt",O_WRONLY | O_CREAT); if (fd2 == -1) { perror("open"); } int ret = 0; char buf[SIZE] = {0}; while (ret = read(fd1,buf,SIZE)) { if (ret == -1) { perror ("raed"); break; } write (fd2,buf,ret); } printf ("文件复制成功\n"); close (fd1); close (fd2);标准I/O函数:
函数原型:
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream); size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);代码示例:
FILE *fp1 = fopen("1.ppt","a"); if(fp1 == NULL) { perror("fopen"); return -1; } FILE *fp2 = fopen("1.ppt","a"); if(fp2 == NULL) { perror("fopen"); return -1; } printf ("文件打开成功\n"); int ret = 0; char buf[SIZE] = {0}; while (ret = fread(buf,sizeof(char),SIZE,fp1)) { fwrite(buf,sizeof(char),ret,fp2); } if (ret == 0 && !feof(fp1)) { perror ("fraed"); return -1; } printf ("文件复制成功\n");
3、移动文件偏移指针:
系统调用函数:
函数原型:
off_t lseek(int fildes, off_t offset, int whence);代码示例1:
int fd; if ((fd = open("test",O_RDWR | O_CREAT,0777)) == -1) { printf ("文件打开失败\n"); perror ("open"); } lseek (fd,15,SEEK_SET); write(fd,"abc",4); close(fd);代码实例2:(建一个1G的大文件)
int fd; if ((fd = open("big",O_RDWR | O_CREAT,0777)) == -1) { printf ("文件打开失败\n"); perror ("open"); } lseek (fd,1024*1024*1024,SEEK_SET); write(fd,"\0",1); close(fd);关于文件编程的更多函数及其使用,欢迎大家一起交流。