Linux文件非读写操作
access()
#include <unistd.h>
int access(const char *pathname, int mode);
if(0==access("./a.txt",F_OK))
printf("file exists\n")
if(0==access("./a.txt",R_OK))
printf("file exists and grants read permission\n")
fstat()、stat()、lstat()
#include<unistd.h>
#include<sys/stat.h>
#include<sys/types.h>
int fstat(int fd, struct stat *buf);
int stat (const char *pathname, struct stat *buf);
int lstat(const char *pathname, struct stat *buf);
ino_t st_ino;
mode_t st_mode;
nlink_t st_nlink;
uid_t st_uid;
gid_t st_gid;
dev_t st_rdev;
off_t st_size;
blksize_t st_blksize;
blkcnt_t st_blocks;
time_t st_atime;
time_t st_mtime;
time_t st_ctime;
};
一些POSIX宏可以用来检查文件类型
S_ISREG(m)
S_ISDIR(m)
S_ISCHR(m)
S_ISBLK(m)
S_ISFIFO(m)
S_ISLNK(m)
S_ISSOCK(m)
*/
获取文件大小
- fseek()把offset移到SEEK_END, 再用ftell()返回文件的大小
- lseek() , 返回文件的大小
3.stat(), struct stat st; st.st_size的数值就是文件大小
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(){
struct stat st={};
int res=stat("./a.txt",&st);
if(-1==res)
printf("stat"),exit(-1);
printf("st_mode=%o,st_size=%ld,st_mtime=%ld\n",st.st_mode,st.st_size,st.st_mtime);
if(S_ISREG(st.st_mode))
printf("Regular file\n");
if(S_ISDIR(st.st_mode))
printf("Dir file\n");
printf("file prot:%o\n",st.st_mode&0777);
printf("file size:%ld\n",st.st_size);
printf("latest modify:%s",ctime(&st.st_mtime));
struct tm* pt=localtime(&st.st_mtime);
printf("latest modify:%d-%d-%d-%02d:%02d:%02d\n",
1900+pt->tm_year,1+pt->tm_mon,pt->tm_mday,pt->tm_hour,pt->tm_min,pt->tm_sec);
return 0;
}
chmod()、fchmod():
#include <sys/stat.h>
int chmod(const char *path, mode_t mode);
int fchmod(int fd, mode_t mode);
truncate()、ftruncate():
#include <unistd.h>
#include <sys/types.h>
int truncate(const char *path, off_t length);
int ftruncate(int fd, off_t length);
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<stdlib.h>
int res=chmod("a.txt",0600);
if(-1==res)
perror("chmod"),exit(-1);
int res=truncate("a.txt",100);
if(-1==res)
perror("truncate"),exit(-1);
#include<unistd.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/mman.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct{
int id;
char name[20];
double salary;
}Emp;
int main(){
int fd=open("./emp.dat",O_RDWR|O_TRUNC|O_CREAT,0664);
if(-1==fd)
perror("open"),exit(-1);
printf("open success\n");
int res=ftruncate(fd,3*sizeof(Emp));
if(-1==res)
perror("ftruncate"),exit(-1);
void* pv=mmap(NULL,3*sizeof(Emp),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
if((void*)-1==pv)
perror("mmap"),exit(-1);
Emp *pe=pv;
pe[0].id=1001;strcpy(pe[0].name,"zhangfei");pe[0].salary=3000;
pe[1].id=1002;strcpy(pe[1].name,"guanyu");pe[1].salary=3500;
pe[2].id=1003;strcpy(pe[2].name,"liubei");pe[2].salary=4000;
printf("map success\n");
res=munmap(pv,3*sizeof(Emp));
if(-1==res)
perror("munmap"),exit(-1);
printf("unmap success\n");
res=close(fd);
if(-1==res)
perror("close"),exit(-1);
printf("close success\n");
return 0;
}