Linux系统常用文件IO函数

常用文件IO函数

在这里插入图片描述

1. 打开文件(open函数)

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
功能:
    打开文件,如果文件不存在则可以选择创建。
参数:
    pathname:文件的路径及文件名
    flags:打开文件的行为标志,必选项 O_RDONLY(以只读的方式打开), O_WRONLY(以只写的方式打开), O_RDWR(以可读、可写的方式打开)。
    mode:这个参数,只有在文件不存在时有效,指新建文件时指定文件的权限
返回值:
    成功:成功返回打开的文件描述符
    失败:-1
  • flags详细说明:
    可选项,和必选项按位或起来,如:O_RDWR | O_CREAT
    O_CREAT 文件不存在则创建文件,使用此选项时需使用mode说明文件的权限
    O_EXCL 如果同时指定了O_CREAT,且文件已经存在,则出错
    O_TRUNC 如果文件存在,则清空文件内容
    O_APPEND 写文件时,数据添加到文件末尾
    O_NONBLOCK 对于设备文件, 以O_NONBLOCK方式打开可以做非阻塞I/O

  • mode补充说明
    1- 文件最终权限:mode & ~umask
    2- shell进程的umask掩码可以用umask命令查看
    Ø umask:查看掩码(补码)
    Ø umask mode:设置掩码,mode为八进制数
    Ø umask -S:查看各组用户的默认操作权限
    在这里插入图片描述

代码1:打开一个文件夹

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
//打开文件
int main()
{
	int fd;
	fd=	open("./file1",O_RDWR);
	printf("fd=%d\n",fd);
	return 0;
}

代码2:打开新建的文件

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
//创建并打开文件
int main()
{
	int fd;

	fd=	open("./file1",O_RDWR);
	if(fd==-1)
	{
	  printf("open file failed\n");
	    //打开创建的文件
	    fd=	open("./file1",O_RDWR|O_CREAT,0600);//0600表示:文件权限可读(4)可写(2)
	    if(fd>0)
	    {
		printf("create file1\n");
	    }
	}
	return 0;
}

2. 创建文件 creat 函数

在这里插入图片描述

3. 关闭文件(close函数)

#include <unistd.h>int close(int fd);
功能:
    关闭已打开的文件
参数:
    fd : 文件描述符,open()的返回值
返回值:
    成功:0
    失败: -1, 并设置errno

4. 写文件(write函数)


#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
功能:
    把指定数目的数据写到文件(fd)
参数:
    fd :  文件描述符
    buf : 数据首地址
    count : 写入数据的长度(字节)
返回值:
    成功:实际写入数据的字节个数
    失败: - 1

代码1:数据写入文件

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include <unistd.h>
#include<string.h>
//创建文件 并打开文件 并写入文件
int main()
{
	int fd;
	char *buf="hahahahahahaha heihei ";//写入的数据
	fd=	open("./file1",O_RDWR);
	if(fd==-1)
	{
	     printf("open file failed\n");
	     
	     //O_CREAT 若文件不存在则创建它 O_TRUNC 把文件原内容清空
		fd=	open("./file1",O_RDWR|O_CREAT|O_TRUNC,0600);
		if(fd>0)
		{
			printf("create file1\n");
		}
	}
	printf("open suscees: fb =%d\n",fd);
	write(fd,buf,strlen(buf));//写数据
	close(fd);
	return 0;
}

5. 读文件(read函数)

#include <unistd.h>ssize_t read(int fd, void *buf, size_t count);
功能:
    把指定数目的数据读到内存(缓冲区)
参数:
    fd : 文件描述符
    buf : 内存首地址
    count : 读取的字节个数
返回值:
    成功:实际读取到的字节个数
    失败: - 1

示例代码:打开文件并写入数据,并读出写入的数据

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include <unistd.h>
#include<string.h>
#include<stdlib.h>
//创建文件 并打开文件 并写入文件
int main()

{
	int fd;
	char *buf="hahahahahah gewenchen";//定义一个写入的数据
	fd=	open("./file1",O_RDWR);//打开file1文件
	if(fd==-1)//判断是否打开成功
	{
	     printf("(没有找到文件,文件打开失败!)\n");//打开失败
		fd=	open("./file1",O_RDWR|O_CREAT,0600);//创建file1文件 权限是可读可写 可执行
		if(fd>0)//判断是否创建成功
		{
			printf("重新创建文件,并创建成功!)\n");//文件创建成功
		}
	}

	printf("文件打开成功(open suscees): fb =%d\n",fd);//文件打开成功
	
	printf("文件准备写入数据!\n");	
	//写数据
	int n_write=write(fd,buf,strlen(buf));
		if(n_write!=-1)
		{
			printf("写入数据-write %d byte to file\n",n_write);
	
		}

	printf("写入数据完毕,准备关闭!\n");
	close(fd);
	
	printf("准备读取文件内容!\n");
	
	fd=	open("./file1",O_RDWR);//打开file1文件
	if(fd==-1)//判断是否打开成功
	{
	     printf("open file failed(文件打开失败!)\n");//打开失败
	}	
	printf("开始读取文件!\n");
	
	char *readBuf;
	readBuf=(char*)malloc(sizeof(char)*n_write+1);//读文件里的数据
	int n_read=read(fd,readBuf,n_write);
	printf("文件大小 :read:%d\n文件内容为:%s\n",n_read,readBuf);

	close(fd);
	return 0;
}

6. 文件光标位置(lseek函数)

#include <sys/types.h>
#include <unistd.h>off_t lseek(int fd, off_t offset, int whence);
功能:
    改变文件的偏移量
参数:
    fd:文件描述符
    offset:根据whence来移动的位移数(偏移量),可以是正数,也可以负数,如果正数,则相对于whence往右移动,如果是负数,则相对于whence往左移动。如果向前移动的字节数超过了文件开头则出错返回,如果向后移动的字节数超过了文件末尾,再次写入时将增大文件尺寸。
​
    whence:其取值如下:
        SEEK_SET:从文件开头移动offset个字节
        SEEK_CUR:从当前位置移动offset个字节
        SEEK_END:从文件末尾移动offset个字节
返回值:
    若lseek成功执行, 则返回新的偏移量
    如果失败, 返回-1

所有打开的文件都有一个当前文件偏移量(current file offset),以下简称为 cfo。cfo 通常是一个非负整数,用于表明文件开始处到文件当前位置的字节数。

读写操作通常开始于 cfo,并且使 cfo 增大,增量为读写的字节数。文件被打开时,cfo 会被初始化为 0,除非使用了 O_APPEND 。

7. 实现 linux cp 命令的代码

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

 //把文件1的内容复制到文件2

int main(int argc, char **argv)
{

    int fdSrc;//源文件
    int fdDes;//目标文件
    //char readBuf[1024]={0};
   char *readBuf=NULL;
 
    if(argc != 3)//参数判断
    {
        printf("pararm error\n");
        exit(-1);
    }

    //打开argv[1]所指的源文件
    if((fdSrc=open(argv[1], O_RDWR)) == -1)   
    {   
        printf("Open Error\n");   
        exit(1);   
    } 

    //打开argv[1]所指的源文件
    //fdSrc = open(argv[1],O_RDWR);

    //测得文件大小
    int BUFFER_SIZE = lseek(fdSrc,0,SEEK_END);
    lseek(fdSrc,0,SEEK_SET);//光标放到文件头
    printf("读取的文件大小为: %d\n",BUFFER_SIZE);  
 

    //读取文件
    readBuf=(char *)malloc(sizeof(char)*BUFFER_SIZE + 4);//开辟空间
    int n_read = read(fdSrc, readBuf, BUFFER_SIZE);// //把argv[1]所指的文件内容读读到readBuf中
    if(n_read==-1)  
    {  
        printf("文件读取失败!\n");   
        exit(1);          
    }
     
     printf("开始拷贝文件,请稍等》》》》》\n");   
    //打开文件
    fdDes = open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0600);//O_CREAT 若文件不存在则创建它 O_TRUNC 把文件原内容清空

    //把读取的数据写入新文件
    int n_write = write(fdDes,readBuf,strlen(readBuf));
    printf("文件拷贝完毕!\n");   
      
    close(fdSrc);
    close(fdDes);
 
    return 0;
}

使用方法:

8.搜索字符串 strstr() 函数

头文件:<string.h>
函数原型:
char *strstr(char *str1, const char *str2);   //返回值为字符型指针
str1: 被查找目标
str2: 要查找对象
 
函数作用:
1strstr() 函数搜索一个字符串在另一个字符串中的第一次出现。
2、找到所搜索的字符串,则该函数返回第一次匹配的字符串的地址;
3、如果未找到所搜索的字符串,则返回NULL

9. 实现修改文件里的内容

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
 //实现功能把文件A中的LENG=3,修改成LENG=5.
int main(int argc, char **argv)
{
    int fdSrc;//定义一个文件描述符
 
    char *readBuf=NULL;
 
    if(argc != 2){
        printf("pararm error\n");
        exit(-1);
    }
     
    fdSrc = open(argv[1],O_RDWR);//打开要修改的配置文件(argv[1]所指的文件)
    int size = lseek(fdSrc,0,SEEK_END);
    lseek(fdSrc,0,SEEK_SET);
 
    readBuf=(char *)malloc(sizeof(char)*size + 8);//开辟临时空间 +8是多开了8个做冗余。

    int n_read = read(fdSrc, readBuf, size);


	//定义要查找的对象 本次查对象为:LENG=	
    char *p = strstr(readBuf,"LENG=");//要在readBuf中查找LENG=
    if(p==NULL){
        printf("not found\n");
        exit(-1);
    }
     
    p = p+strlen("LENG=");//找到后 移动strlen个字符
    *p = '5';//替换要修改的内容
         
    lseek(fdSrc,0,SEEK_SET);//文件光标复位。
    int n_write = write(fdSrc,readBuf,strlen(readBuf));
 
    close(fdSrc);
 
    return 0;
}

补充

**int main(int argc, char **argv)说明

#include <stdio.h>
int main(int argc, char **argv)
{
    printf("totol params: %d\n",argc);
    printf("No.1 params :%s\n",argv[0]);
    printf("No.2 params :%s\n",argv[1]);
    printf("No.3 params :%s\n",argv[2]);
 
    return 0;
}

**int main(int argc, char **argv)说明:
在这里插入图片描述

//文件echoarg.c
#include <stdio.h>

int main(int argc,char *argv[])
{
    int i = 0;
    for(i = 0; i < argc; i++)
    {
        printf("argv[%d]: %s\n",i,argv[i]); 
    }
    return 0;
}

运行结果:
在这里插入图片描述

其它

代码1:

#include <stdio.h>
#include <string.h>
 
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
 
#define SIZE 128 //定义数据大小
int main(void)
{
    int fd = -1;
    int ret = -1;
 
    char buf[SIZE];//定义一个数据
 
    //1. 打开一个终端设备  该设备默认是阻塞的
    //fd = open("/dev/tty", O_RDWR);
    fd = open("/dev/tty", O_RDWR | O_NONBLOCK);
    if (-1 == fd)
    {
        perror("open"); 
        goto err0;
    }
    //2. 读设备
    memset(buf, 0, SIZE);//初始化数据
    ret = read(fd, buf, SIZE);
    if (ret <= 0)
    {
        perror("read"); 
    }
    printf("buf:%s\n", buf);
    //3. 关闭文件
    close(fd);
 
    return 0;
err0:
    return 1;
}

INADDR_ANY通配地址 值为0;


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值