常用指令

1.打开:open

2.关闭:close

3.写:write

4.读:read

5.光标偏移:lseek

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--文件的路径

flag:下面的宏定义必须选择一个

1.O_RDONLY  -- 只读

2.O_WRONLY  -- 只写

       3. O_RDWR  -- 读写

下面的宏可选:

O_CREAT -- 文件不存在,创建,存在,不起作用----最常用

O_TRUNC -- 清空写

O_APPEND -- 追加写

mode:如果flag里面用了O_CREAT,此时需要提供第三个参数,第三个参数就是文件的权限;

eg:

//打开1.txt 读写,文件不存在,创建
open(“1.txt”,O_RDWR|O_CREAT,0777);
//打开2.txt 读写,文件不存在,创建,存在,清空写:
open(“2.txt”,O_RDWR|O_CREAT|O_TRUNC,0777);

2.关闭:close

头文件

#include <unistd.h>
int close(int fd);
形参:open的返回值
返回值:close()  returns  zero on success. 
 On error, -1 is returned

3.写:write

头文件

#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
形参:fd -- open的返回值
 buf:要写入的内容的首地址
count:写入的字节数
返回值:成功真正写入的字节数,On error, -1 is returned

4.读:read

头文件

#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
形参:fd -- open的返回值
 buf:读取之后要保存的位置的首地址
count:读取的字节数
返回值:成功真正读取到的字节数(读到文件末尾,返回0),On error, -1 is returned;

5.光标偏移:lseek

头文件

#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset,int whence);
形参:
fp:open的返回值
offset:偏移量(+往文件末尾方向偏移,-往文件开头偏移)
whence:SEEK_SET  0
         SEEK_CUR  1
         SEEK_END  2
         返回值:先做后面的光标偏移,返回光标偏移之后的位置到文件开头的偏移量;

例题:1

实现一个cp的功能 (非缓冲区的文件操作):格式:./a.out 1.txt 2.txt   将1.txt复制一份,命名为2.txt
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include<fcntl.h>
int main(int argc,char *argv[])
{
	//创建并打开文件2.txt
	int pf=open(argv[1],O_RDWR|O_CREAT,0664);
	//写入数据信息
	char m[1024]="hello junjun";
	write(pf,m,strlen(m));
	//写入完毕,关闭文件
	close(pf);
	//重新打开并读取信息
	int ppf=open(argv[1],O_RDONLY);
	//读取信息
	char m1[1024];
	read(ppf,m1,strlen(m));
	//写一个新的文件3.txt
	int pppf=open(argv[2],O_RDWR|O_CREAT,0664);
	//将读取2.txt的内容写入其中
	write(pppf,m1,strlen(m));
	//关闭文件
	close(ppf);
	close(pppf);
	return 0;
}

例题:2

定义结构体,两个成员,一个账号,一个密码 先设置账号密码 读取1.c写入的结构体
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include<string.h>
#include<fcntl.h>
struct aa
{
	char zhanghu[1024];
	char passwd[1024];
};
void save(struct aa *a);

int main()
{
	struct aa s;
	save(&s);
	return 0;
}
void save(struct aa *a)
{
	//初始化账户密码
	strcpy(a->zhanghu,"123456");
	strcpy(a->passwd,"123456");
	//打开文件1.txt
	int p=open("1.txt",O_RDWR|O_CREAT,0664);
	//写入账户密码到1.txt
	write(p,&a,strlen(a->zhanghu)+strlen(a->passwd));
	close(p);//写完关闭1.txt
	//现在输入账号密码进行比对
	struct aa temp1;
	printf("请输入账号:\n");
	scanf("%s",temp1.zhanghu);
	printf("请输入密码\n");
	scanf("%s",temp1.passwd);
	if(strcmp(a->zhanghu,temp1.zhanghu)==0&&strcmp(a->passwd,temp1.passwd)==0)
	{
		printf("账户密码正确\n");
	}
	else 
	{
		printf("账户错误或密码错误\n");
	}
}