嵌入式自学第二十六天(5.22)
(1)文件查找:lseek
例:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char **argv)
{
int fd = open("1.txt",O_WRONLY|O_CREAT|O_TRUNC,0666);
if(-1 == fd)
{
printf("open error");
return 1;
}
off_t offset = lseek(fd,1024*1024*10,SEEK_SET);
printf("%ld\n",offset);
write(fd,"a",2);
close(fd);
//system("pause");
return 0;
}
注意:第三个参数跟fseek一样
(2)文件流转文件描述符:fileno
例:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv)
{
FILE* fp = fopen("1.txt","w");
if(NULL == fp)
{
return 1;
}
int fd = fileno(fp);
write(fd,"hello",5);
//close(); fclose();
fclose(fp);
//system("pause");
return 0;
}
注意:关闭文件采用fclose,因为封装的比没封的功能全一些。
(3)文件描述符转文件流:fdopen
例:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char **argv)
{
int fd = open("1.txt",O_RDONLY);
if(-1 == fd)
{
return 1;
}
FILE* fp = fdopen(fd,"r");
if(NULL == fp)
{
return 1;
}
char buf[512]={0};
fgets(buf,sizeof(buf),fp);
printf("%s",buf);
fclose(fp);
//system("pause");
return 0;
}
(4)错误定位及原因打印:
#include <stdio.h>
#include <errno.h> // extern int errno;
int main(int argc, char **argv)
{
perror("aaa");
FILE* fp = fopen("10.txt","r");
if(NULL == fp)
{
printf("errno %d\n",errno);
perror("fopen main.c:10");
return 0;
}
//system("pause");
return 0;
}
注意:int errno 错误号,系统定义的变量
perror(“提示”)出错后,提示符后面自动加上原因
(5)目录操作:opendir、readdir、closedir
例:
#include <dirent.h>
#include <stdio.h>
#include <sys/types.h>
int main(int argc, char **argv)
{
DIR *dir = opendir("../");
if (NULL == dir)
{
perror("opendir"); // stderr
return 1;
}
while (1)
{
struct dirent *info = readdir(dir);
if (NULL == info)
{
break;
}
printf("%s\t\t", info->d_name);
switch (info->d_type)
{
case DT_BLK:
printf("块设备\n");
break;
case DT_DIR:
printf("目录文件\n");
break;
case DT_REG:
printf("普通文件\n");
break;
default:
printf("其他文件\n");
}
}
closedir(dir);
// system("pause");
return 0;
}
注意:目录流DIR* dir指向目录
linux文件类型:dir.type
man readdir
DT_BLK block device 块设备,存储类b
字符设备 DT_CHR 鼠标 键盘c
DT_DIR 目录d
DT_FIFO 管道 pipe p makefifo pipe ll
DT_LNK 符号链接,软链接 l
DT_REG 规则文件 普通
DT_SOCK 网络文件
命令ll -i 得文件编号inode
(6)时间函数:
man 3 time
从1970年统计总秒数
time_t a = time(time_t *tloc)传NULL 或者long返回秒数
man 3 localtime
1900年开始记统计年数,t.year
struct tm * t = localtime(const char *)
例:
#include <stdio.h>
#include <time.h>
int main(int argc, char **argv)
{
time_t tm;
tm = time(NULL);
printf("%ld\n",tm);
struct tm * tminfo = localtime(&tm);
printf("%d-%d-%d %d:%d:%d\n",tminfo->tm_year+1900,tminfo->tm_mon+1,tminfo->tm_mday
,tminfo->tm_hour,tminfo->tm_min,tminfo->tm_sec);
//system("pause");
return 0;
}