上节学习了如何用系统调用的方法来访问与读写文件等,本节介绍利用C函数的库来访问文件,该方法不仅适用于Linux系统,在其他系统平台上均可用,它是一种类似与系统的接口。
C语言库函数访问文件
库函数与系统调用不同的是,没有文件描述符,fd是一个FILE指针。
FILE *fopen(const char *pathname,const char *mode)
模式有:r,rb(只读)w,wb(只写),a,ab(追加),r+,rb+(读写)等,b为二进制
size_t fread(void *ptr,size_t size,size_t n,FILE *fstream),从stream文件中读取n个字段,每个字段为size个字节到ptr中。返回实际已读的数据量。
size_t fwrite(void *ptr,size_t size,size_t n,FILE *fstream)
int fgetc(FILE *stream)从指定的文件中读取一个字符。putchar(ch),在屏幕上打印一个字符。int putc(int c,FILE *stream)向指定的文件中写一个字符。
格式化输出到一个流中,eg:fprintf(FILE *stream,"%s",s)
int fseek(FILE *stream,long offset,int whence),和系统调用里的lseek函数类似。
路径获取函数:char *getcwd(char *buffer,size_t size);该函数提供size大小的buffer,将当前路径拷贝到这个buffer,如果buffer太小,返回-1.
创建目录函数int mkdir(char *dir,int mode),0表示成功,-1出错。
头文件,stdio.h:待缓冲的标准输入输出函数,如printf和scanf。
stdlib.h:封装了一些类型(size_t,div_t,ldiv_t),宏(EXIT_FAILURE,EXIT_SUCCESS)常用的函数(malloc,free,exit,rand)
process.h:提供了对多线程支持的函数。
unistd.h:UNIX系统服务的函数原型,相当于windows的windows.h
sys/stat.h:Linux系统中对文件的操作。
下面介绍时间编程
日历时间:以某一时间点为标准。
一、tm结构
#include <time.h>
#include <stdio.h>
int main(void)
{
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;
}
二、时间显示
char *asctime(const struct tm *tm);//将tm格式的时间转换成字符串
char *ctime(const time_t *timep);//将日历时间转换成本地时间的字符串形式。
对上述程序可以修改如下:
#include <time.h>
#include <stdio.h>
int main(void)
{
struct tm *local;
time_t t;
//获取日历时间
t=time(NULL);
//将日历时间转化成本地时间
local=localtime(&t);
printf(asctime(local));
printf(ctime(&t));
return 0;
}
三、获取今日凌晨到现在的时间差,常用于计算事件耗时:
int gettimeofday(struct timeval *tv,struct timezone *tz)
eg:
#include <sys/time.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void function()
{
unsigned int i,j;
double y;
for(i=0;i<1000;i++)
for(j=0;j<1000;j++)
y++;
}
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",timeuse);
exit(0);
}
四、延时执行
unsigned int sleep(unsigned int seconds);//使程序睡眠多少秒
void usleep(unsigned long usec);//程序睡眠多少微秒