Linux篇:文件打开、创建与读写

一.文件打开与创建

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

Pathname:要打开的文件名(含路径,缺省为当前路径)

Flags:O_RDONLY只读打开          O_WRONLY只写打开          O_RDWR可读可写打开

编写代码

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

int main()
{
   int fd;
   fd=open("./file",O_RDWR);
  printf("fd=%d\n",fd);
  return 0;
}

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

int main()
{
   int fd;
   fd=open("./file",O_RDWR);
   if(fd=-1)
   {
   printf("open file1 failed\n");
  fd =open("./filed",O_RDWR|O_CREAT,0600);
   if(fd>0){
   printf("creat file1 success!\n");
}
}

  return 0;
}
~   

ls  -l   列出所有清单

可读 r  可写w  执行x      可读可写rw

二.文件写入

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

int main()
{
   int fd;
   char *buf ="zhongguo jiayou!"
   fd=open("./file",O_RDWR);
   if(fd=-1)
   {
   printf("open file1 failed\n");
  fd =open("./filed",O_RDWR|O_CREAT,0600);
   if(fd>0){
   printf("creat file1 success!\n");
}
}
  printf("open susceess:fd=%d\n",fd)



   write(fd,buf,sizeof(buf));
  close(fd);
  return 0;
}

 

读取文件

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

int main()
{
   int fd;
   char *buf ="zhongguo jiayou!";
   fd=open("./file",O_RDWR);
   if(fd=-1)
   {
   printf("open file1 failed\n");
  fd =open("./filed",O_RDWR|O_CREAT,0600);
   if(fd>0){
   printf("creat file1 success!\n");
}
}
  printf("open susceess:fd=%d\n",fd);



  int n_write=write(fd,buf,sizeof(buf));
 if(n_write!=-1)
{
printf("write %d byte to file\n",n_write);
}

 char *readBuf;
 readBuf=(char *)malloc(sizeof(char)*n_write+1);

 int n_read=read(fd,readBuf,n_write);


 printf("read %d,context:%s\n",n_read,readBuf);
  close(fd);
  return 0;
}

在Linux中要操作一个文件,一般是先open打开一个文件,得到文件描述符,然后对文件进行读写操作(其他操作),最后是close关闭文件即可。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值