Linux编程学习笔记:文件、时间编程

一、系统调用-文件访问

    Linux中文件编程可以使用两种方法

        Linux系统调用

        C语言库函数

    前者依赖LInux系统,后者与操作系统独立,在任何操作系统下库函数操作文件的方法都是相同的

    创建

        int creat(const char *filename,mode_t mode)

        filename  包含路径,缺省为当前路径

        常见创建模式:S_IRUSRS_IWUSRS_IXUSRS_IRWXU

        除了用宏也可以用1,2,4的组合

        创建文件示例

#include <stdio.h>
#include <stdlib.h>


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

void create_file (char *filename)
{
	if(creat(filename,0755)<0)
	{
		printf("create file %s failure!\n",filename);
	}
	else
	{
		printf("create file %s success!\n",filename);
	}
}

int main(int argc,char *argv[])
{
	int i;
	if(argc<2)
	{
		perror("you haven't input the filename,please try again!\n");
		exit(EXIT_FAILURE);
	}
	for(i=1;i<argc;i++)
	{
		create_file(argv[i]);
	}
	exit(EXIT_SUCCESS);
}

        运行效果

[gyy@localhost file]$ gcc file_create.c -o  file_create
[gyy@localhost file]$ ./file_create hello
create file hello success!
[gyy@localhost file]$ ls
file_create  file_create.c  hello

    文件描述

        在Linux中,所有打开的文件都对应一个文件描述符,本质是一个非负整数,系统分配,范围0-OPEN_MAX。现在很多系统增加至1024

    打开

        int open(const char *pathname,int flags)

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

        flags 打开标志 pathname同上filename

        常见的打开标志:O_RDONLYO_WRONLYO_RDWRO_APPEND(追加)、O_CREAT(不存在则创建)、O_NOBLOCK(非阻塞)

       使用O_CREAT则需要三个参数

       打开文件示例代码

#include <stdio.h>
#include <stdlib.h>

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

int main(int argc,char *argv[])
{
	int fd;
	if(argc<2)
	{
		puts("Please input the open file pathname!\n");
		exit(1);
	}
	if((fd=open(argv[1],O_CREAT|O_RDWR,0775))<0)
	{
		perror("open file failure!\n");
		exit(1);
	}
	else
	{
		printf("open file %d sucess!\n",fd);
	}
	close(fd);
	exit(0);
}

        运行效果

[gyy@localhost file]$ vim file_open.c
[gyy@localhost file]$ gcc file_open.c -o file_open
[gyy@localhost file]$ ./file_open hello
open file 3 sucess!
[gyy@localhost file]$ ./file_open 123
open file 3 sucess!
[gyy@localhost file]$ ls
123    file_create  file_create.c  file_open  file_open.c  hello
[gyy@localhost file]$ ll
total 32
-rwxrwxr-x 1 gyy gyy    0 Jan 30 15:51 123

        可以看出,hello是存在的文件,会打开,而123不存在则会创建

    关闭

        int close(int fd)

        fd有系统调用open返回

    读

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

        功能:从文件描述符fd所指的文件中读取length个字节到buf所指的缓冲区,返回值为实际读取的字节数

    写

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

        把length个字节从buf指向的缓冲区中写到文件描述符fd所指向的文件中,返回为实际写入的字节数

    定位

        int lseek (int fd,offset_t offset ,int whence)

        将文件读写指针相对whence移动offset个字节,操作成功时返回文件指针相对于文件头的位置

        whence可使用:

            SEEK_SET:相对于文件头

            SEEK_CUR:相对于文件读写指针的当前位置

            SEEK_END:相对于文件末尾

       offset可取负值代表向前移动

        用lseek来确定文件大小:直接移到文件尾返回值就是文件长度

        longth=lseek(fd,0,SEEK_END);

   访问判断

        int access(const char *pathname,int mode)

        mode:R_OKW_OKX_OKF_OK

        返回0,失败返回-1

    综合示例,文件拷贝

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

#define BUFFER_SIZE 1024

int main(int argc,char **argv)
{
	int from_fd,to_fd;
	int bytes_read,bytes_write;
	char buffer[BUFFER_SIZE];
	char *ptr;
	//检测参数
	if(argc!=3)
	{
		fprintf(stderr,"Usage : %s fromfile to file/n/a",argv[0]);
		exit(1);
	}
	//打开源文件
	if((from_fd=open(argv[1],O_RDONLY))==1)
	{
		fprintf(stderr,"Open %s Error:%s\n",argv[1],strerror(errno));
		exit(1);
	}	
	//创建目的文件
	if((to_fd=open(argv[2],O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR))==-1)
	{	
		
		fprintf(stderr,"Open %s Error:%s\n",argv[2],strerror(errno));
	}
	//文件拷贝代码
	while(bytes_read=read(from_fd,buffer,BUFFER_SIZE))
	{
		if((bytes_read==-1)&&(errno!=EINTR))
			break;
		else if(bytes_read>0)
		{
			ptr=buffer;
			while(bytes_write=write(to_fd,ptr,bytes_read))
			{
				if((bytes_write==-1)&&(errno!=EINTR))
					break;
				else if(bytes_write==bytes_read)
					break;
				else if(bytes_write>0)
				{
					ptr+=bytes_write;
					bytes_read-=bytes_write;
				}
			}
			if(bytes_write==-1)
				break;
		}	
	}
	close(from_fd);
	close(to_fd);
	exit(0);
}

    运行效果

[gyy@localhost file]$ gcc file_cp.c -o file_cp
[gyy@localhost file]$ ls
123  file_cp    file_create    file_open    hello
aaa  file_cp.c  file_create.c  file_open.c
[gyy@localhost file]$ vim from_file
[gyy@localhost file]$ cat from_file 
This is a test
This file will be paste to to_file!
[gyy@localhost file]$ ./file_cp from_file to_file
[gyy@localhost file]$ ls
123  file_cp    file_create    file_open    from_file  to_file
aaa  file_cp.c  file_create.c  file_open.c  hello
[gyy@localhost file]$ cat to_file 
This is a test
This file will be paste to to_file!

    运行file_cp后创建了to_file这个文件,并把from_file的内容拷贝了过去

二、库函数文件访问

    独立于操作系统

    可移植性更好

三、时间编程

    UTC:世界标准时间,格林威治时间

    日历时间:1970.1.1 00:00到现在的秒数

    获取秒数

        time_t time(time_t *tloc)

    时间转化

        转化为UTC:struct tm *gmtime(const time_t *timep)

        转化为本地时间:struct tm *localtime(const time_t *timep)

        

    时间转化示例代码

#include <time.h>
#include <stdio.h>

int main()
{
	struct tm *local;
	time_t t;
	t=time(NULL);
	local=localtime(&t);
	printf("Local hour is :%d\n",local->tm_hour);
	local=gmtime(&t);	
	printf("UTC hour is :%d\n",local->tm_hour);
	return 0;
}

    运行效果

[gyy@localhost time]$ gcc time1.c -o time1
[gyy@localhost time]$ ./time1 
Local hour is :20
UTC hour is :12

    时间显示

        char *asctime(const struct tm *tm)

        将tm格式的时间转化为字符串

        char *ctime(const time_t *timep)

        将日历时间转化为本地时间字符串

        时间显示示例代码

#include <time.h>
#include <stdio.h>

int main()
{
	struct tm *ptr;
	time_t lt;
	lt=time(NULL);
	ptr=gmtime(&lt);
	printf("%s\n",asctime(ptr));
	printf("%s\n",ctime(&lt));
	return 0;
}

        运行效果

[gyy@localhost time]$ gcc time2.c -o time2
[gyy@localhost time]$ ./time2
Wed Jan 30 12:06:56 2019
		
Wed Jan 30 20:06:56 2019

    获取时间

        int gettimeofday(struct timeval *tv,struct timezone *tz)

        获取从今日凌晨到现在的时间差,常用于计算时间的耗时

struct timeval
{
int tv_sec;//秒数
int tv_usec;//微秒数
};

        计算耗时示例代码

#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

//一个耗时的循环
void function()
{
	unsigned int i,j;
	double y;
	for(i=0;i<1000;i++)
		for(j=0;j<1000;j++)
			y++;
}

int main()
{
	struct timeval tpstart,tpend;
	float timeuse;
	gettimeofday(&tpstart,NULL);
	function();
	gettimeofday(&tpend,NULL);
	
	//计算执行时间
	timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;
	timeuse/=1000000;
	printf("Used Time: %f\n",timeuse);
	exit(0);
}

        运行效果

[gyy@localhost time]$ gcc time3.c -o time3
[gyy@localhost time]$ ./time3
Used Time: 0.003074

    延时执行

        unsigned int sleep(unsigned int seconds)

        程序睡眠秒

        void usleep(unsigned long usec)

        程序睡眠微秒

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值