2018.08.13

 

 

文件操作:

 在Linux中对目录和设备的操作都等同于对文件的操作,都是使用文件描述符来进行的 。

 Linux文件可分为:普通文件,目录文件,链接文件,设备文件 

 

当打开一个现存文件或创建一个新文件时,内核就向进程返回一个文件描述符;当需要读写文件时,也需要把文件描述符作为参数传递给相应的函数。

 

文件描述符是一个非负的整数,它是一个索引值,并指向在内核中每个进程打开文件的记录表。

 

一个进程启动时,都会打开3个文件:标准输入、标准输出和标准出错处理

文件的创立: 

 

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

int main()
{
	int ret;

	ret = creat("hello.c", S_IRWXU | S_IRWXG | S_IWGRP);
	if (-1 == ret)    //返回值判断
	{
		perror("creat");
		exit(1);
	}

	return 0;
}

文件的打开:

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

int main()
{
	int fd, ret;   //file description  文件描述符
	char buf[64] = "helloworldhelloworld";

#if 0
	fd = open("hello.c", O_RDWR);   //以读写方式打开文件hello.c
	if (-1 == fd)
	{
		perror("open");
		exit(1);
	}

	close(fd);
#endif

	fd = open("hello.txt", O_RDWR | O_CREAT, S_IRWXU);  //创建文件xx.c,并且读写方式打开
	if (-1 == fd)
	{
		perror("open");
		exit(1);
	}

	ret = write(fd, buf, strlen(buf));   //buf写入到hello.txt,strlen(len)写入的长度
	if (-1 == ret)
	{
		perror("write");
		exit(1);
	}

	//ret = lseek(fd, -20, SEEK_END);   //相对某个位置移动某个长度
	ret = lseek(fd, 0, SEEK_SET);   //相对某个位置移动某个长度
	if (-1 == ret)
	{
		perror("lseek");
		exit(1);
	}
	
	memset(buf, 0, sizeof(buf));
	ret = read(fd, buf, sizeof(buf));
	if (ret == -1)
	{
		perror("read");
		exit(1);
	}
	printf("read from txt : %s\n", buf);

	close(fd);
		
	return 0;
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值