Linux文件系统操作

    Linux的文件系统操作调用涉及创建、打开、读写和关闭文件。

    int creat(const char *filename,mode_t mode);

    int open(const char *pathname, int flags);  常用的有 O_RDONLY; O_WRPNLY; O_RDWR; O_CREAT

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

    int read(int fd,const void *buf,size_t length);

    int write(int fd,const void *buf,size_t length);

    定位:对于随机文件,可以随机指定位置读写,使用如下函数进行定位。

    int lseek(int fd, offset_t offset, int whence); 返回值为文件指针相对于文件头的位置。

    int close(int fd);

    

代码例程:

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

#include <stdio.h>

#define LENGTH 100

main()

{

  int fd,len;

  fd = open ("hello.txt", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);

  if (fd) {

    write (fd,"Hello World", strlen("hello world"));

    close(fd);

  }

   fd = open("hello.txt",O_RDWR);

   len = read(fd, str, LENGTH);

   str[len] = '\0';

   printf("%s\n", str);

   close(fd);

}

常用C库文件系统操作:

FILE *fopen(const char *path,const char *mode);

int fgetc(FILE stream);

int fput(int c,FILE *stream);

size_t fread(void *ptr,size_t size,size_t n,FILE *stream);

size_t fwrite(const void *ptr,size_t size,size_t n,FILE *stream);

int fclose(FILE *stream);

例程:

#include <stdio.h>

#define LENGTH 100

main()

{

  FILE *fd;

  char str[LENGTH];

  fd = fopen("hello.txt","w+");

  if (fd) {

     fputs("hello world",fd);

     fclose(fd);

}

fd = fopen("hello.txt","r");

fgets(str,LENGTH,fd);

printf("%s\n",str);

fclose(fd);

}

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值