文件IO【1】

您所在的位置:网站首页 dup和dup2函数的应用实例 文件IO【1】

文件IO【1】

2023-06-04 09:56| 来源: 网络整理| 查看: 265

十,关于光标位置相关的函数(fseek,ftell,rewind)

#include

       int fseek(FILE *stream, long offset, int whence);

功能:修改文件光标位置

        参数1:要修改光标的文件

        参数2:偏移量

                >0:表示向后偏移

                =0:不偏移

                这两条语句相当于求出文件大小

     

 void rewind(FILE *stream);

功能:将光标定位到开头

参数:文件指针

返回值:无

等价于fseek(fp,0,SEEK_SET)

练习:通过代码读取一张图片,对图片进行操作  

#include #include #include int main(int argc,const char *argv[]) { FILE *fp; char buf[10]=""; //以r+形式打开文件 if((fp=fopen("./milaoshu.bmp","r+"))==NULL) { perror("open file"); return -1; } //想要获取文件大小 unsigned int img_size; //将文件光标偏移两字节,前两字节是文件类型 fseek(fp,2,SEEK_SET); //读取文件大小 fread(&img_size,4,1,fp); //输出图片大小 printf("img_size=%d\n",img_size); //向后偏移54字节,得到数据 fseek(fp,54,SEEK_SET); //定义一个颜色 unsigned int color[3]={0xff,0,0}; //遍历图片 for(i=0;i在一个正在执行的程序中,默认打开了三个文件描述符 0(stdin) 1(stdout) 2(stderr)

        3>文件描述符的使用原则:最小未分配原则

        4>一个程序中文件描述符的最大承载量默认为1024

#include #include #include int main(int argc,const char *argv[]) { printf("fileno of stdin=%d\n",stdin->_fileno); printf("fileno of stdout=%d\n",stdout->_fileno); printf("fileno of stderr=%d\n",stderr->_fileno); return 0; } 2.open函数的使用

       #include        #include        #include

       int open(const char *pathname, int flags);        int open(const char *pathname, int flags, mode_t mode);

功能:打开一个文件

参数1:文件路径,跟fopen的第一个参数一致

参数2:打开方式

 O_RDONLY:只读

 O_WRONLY:只写

 O_RDWR:可读可写

=====上面三个必须选择一个=====

 O_CREAT:如果文件不存在,创建一个文件,如果加了该选项,第三个参数一定要加

O_APPEND:追加写

O_TRUNC:清空内容

O_EXCL:判断文件是否存在,如果已经存在了,则open函数置位错误码为:EEXIST

例如:"w+": O_RDWR |O_CREAT |O_TRUNC

             "r": O_RDONLY

参数3:文件权限,创建文件时的权限

              目录的最大权限:0777

              普通文件的最大权限:0666

最终的权限是给定的(mode & ~umask)

        umask:是系统给定的默认的掩码   0002

        更改掩码的指令 umask 数字

返回值:成功返回打开文件的文件描述符,失败返回-1,并置位错误码

#include #include #include #include #include #include int main(int argc,const char *argv[]) { int fd; //定义一个文件描述符 //以读写的模式打开文件 if((fd=open("./open.txt",O_RDWR|O_CREAT|O_TRUNC,0777))==-1) { perror("open file"); return -1; } //关闭文件 close(fd); return 0; }

               

3.umask        umask:创建文件时是系统给定的掩码   0002

        终端上查看掩码:umask

        更改掩码:

        终端更改:umask数字

        代码更改:umask(数值);

        更改掩码的指令 umask 数字

4.close的使用

int close(int fd)

功能:关闭一个文件

参数:要关闭文件的文件标识符

5.read函数的使用

 #include

       ssize_t read(int fd, void *buf, size_t count);

功能:从给定的文件中读取count个数到buf中

参数1:被读取的文件

参数2:读取后数据存放的容器指针,是一个万能指针,也就是可以读取任意类型的数据

参数3:读取的个数

返回值:>0:读取字符的个数

               0:读取字符的个数

               0向后偏移



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3