Linux系统编程篇(文件)编程操作 一创建,打开,写入,读取,光标(lseek)

open 函数参数说明

 // 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);

int creat(const char *pathname, mode_t mode);
//返回值  文件描述符(非负整数)
//失败    -1
//int openat(int dirfd, const char *pathname, int flags);
//int openat(int dirfd, const char *pathname, int flags, mode_t mode);
/*
pathname: 要打开的文件名;
flage:1.O_RDONLY 只读打开
	  2.O_WRONLY 只写打开
      3.O_RDWR 可读可写打开
	  4.O_CREAT 若文件不存在我们则创建他,使用此选项,需要说明新文件的存取许可权限
mode:创建模式 ,下图
    (user)
    可执行(0100) :S_IXUSR
    可写  (0200) :S_IWUSRL
    可读  (0400) :S_IRUSR
    可读、可写、可执行(0700):S_IRWXU
*/

在这里插入图片描述

创建文件

//int creat(const char *pathname, mode_t mode);
int fd;//为文件描述符
fd=creat("/home/xin/桌面/file2",0700);//可写,可读,可执行
//fd=creat("./file2",0600);

打开文件

//1.int open(const char *pathname, int flags);
//2.int open(const char *pathname, int flags, mode_t mode);
//第一种,文件已经创建好,直接打开
 int fd;
 fd=open("./file2",O_RDWR);//可读可写
//第二种,打开失败,自己创建一个文件
 fd= open("./file2",O_RDWR|O_CREAT,0700);
	

写入文件

在这里插入图片描述

//头文件
#include <unistd.h>
write(fd,buf,strlen(buf));
close(fd);//写入之后关闭

读取

在这里插入图片描述

//头文件
#include <unistd.h>
read(fd,buf,strlen(buf));

实例
#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="中国好,好中国!";
//      fd=creat("/home/xin/桌面/file2",0600);//可写,可读
        fd=open("./file2",O_RDWR);//可读可写
        if(fd<0){
                printf("打开file2失败,fd=%d\n",fd);
                fd=open("./file2",O_RDWR|O_CREAT,0600);
                if(fd>=0){
                        printf("打开file2成功,fd=%d\n",fd);
                }
        }
        int n_write= write(fd,buf,strlen(buf));
        if(n_write!=-1){
                printf("写入成功!,%dbyte\n",n_write);
        }
 		close(fd);
        fd=open("./file2",O_RDWR);
        char *readbuf=(char *)malloc(strlen(buf+1));// 分配空间,避免野指针
        memset(readbuf,'\0',strlen(buf+1));//初始化,可要可不要
        int n_read=read(fd,readbuf,strlen(buf));
        if(n_read!=0){
                printf("%d,%s\n",n_read,readbuf);
        }
        return 0;
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值