Linux编程学习摘记(2)

如果我们打开文件成功,open会返回一个文件描述符.我们以后对文件的所有操作就可以对这个文件描述符进行操作了.
Copy文件的例子代码:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#define BUFFER_SIZE 1024
int main(int argc , char **argv)
{
int from_fd;
int to_fd;
int bytes_read;
int bytes_write;
char buffer[BUFFER_SIZE];
char * ptr;
if(argc != 3){
fprintf(stderr,"Usage:%s fromfile tofile\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);
}
//create destination file
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));
exit(1);
}
//this is a segment of classical codes about copy's operation.
while(bytes_read = read(from_fd,buffer,BUFFER_SIZE)){
//error appeared
if((bytes_read == -1) && (errno != EINTR))
break;
else if(bytes_read > 0){
ptr = buffer;
while(bytes_write = write(to_fd,ptr,bytes_read)){
//error appeared
if((bytes_write == -1) && (errno != EINTR))
break;
//write is all of read buffer
else if(bytes_write == bytes_read)
break;
//write is a part of read buffer, continue write.
else if(bytes_write > 0){
ptr += bytes_write;
bytes_read -= bytes_write;
}
}
//error appeared when writing.
if(bytes_write == -1)
break;
}
}
return 0;
}
文件的属性
文件的属性包括:访问权限,时间,大小等等。
如果判断文件是否可以进行某种操作,可以用Access函数。
其它属性使用stat和fstat来获得。
当前工作路径用getcwd函数获得。
还有很多常用的函数,比如:
mkdir
opendir
dirent
rewinddir
telldir
seekdir
closedir
下面例子演示各种文件操作。
//Get specific file's attrib. The file is a file or directory.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <sys/stat.h>
#include <dirent.h>
static int get_file_size_time(const char * filename)
{
struct stat statbuf;
if(stat(filename , &statbuf) == -1){
printf("Get stat on %s Error : %s\n",filename,strerror(errno));
return (-1);
}
if(S_ISDIR(statbuf.st_mode))
return(1);
if(S_ISREG(statbuf.st_mode))
printf("%s size: %ld bytes \t modified at %s",filename,statbuf.st_size,ctime(&statbuf.st_mtime));
return 0;
}
int main(int argc , char **argv)
{
DIR * dirp;
struct dirent * direntp;
int stats;
if(argc != 2){
printf("Usage: %s filename \n\a",argv[0]);
exit(1);
}
stats = get_file_size_time(argv[1]);
if(stats  == 0 || stats == -1)
exit(1);
if((dirp = opendir(argv[1])) == NULL){
printf("Open Directioy %s Error:%s \n",argv[1],strerror(errno));
exit(1);
}
while((direntp = readdir(dirp)) != NULL){
if(get_file_size_time(direntp->d_name))
closedir(dirp);
}
return 0;
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzwxyg.html