03_io_and_dir
1. ssize_t write(int fd,void *buf,size_t size);
fd : File descriptor
buf : The data you want to write into a kernal object.
size_t size : The size of the data you want to write.
return value :
>0 : The number of bytes written is returned(zero indicates nothing was written)
-1 : On error
2. ssize_t read(int fd,void *buf,size_t size);
buf : Used to store the data you are going to read.
size : The size of buf.
return value :
>0 : The number of bytes read is returned(Zero indicates end of file).
-1 : On error.
3. Descriptor :
0 : The descriptor of stdin
1 : The descriptor of stdout
2 : The descriptor of stderror
4. Empty a buf
memset(buf,0,32)
bzero(buf,32)
5. dir-related
chdir : Change working directory
mkdir : Create a dir
rmdir : Remove a dir
unlink : Remove a file
umask :
1 #include<fcntl.h>
2 #include<stdio.h>
3 #include<stdlib.h>
4 #include<string.h>
5 #include<unistd.h>
6 main()
7 {
8 int fd;
9 int r;
10 char buf[1025];
11 bzero(buf,1024);
12
13 fd = open("test.txt",O_RDWR);
14 if(fd == -1)
15 return;
16
17 while((r = read(fd,buf,1024)) > 0)
18 {
19 buf[r] = 0;
20 printf("%s",buf);
21 }
22
23 close(fd);
24 }
//How to traverse a dir
#include<unistd.h>
#include<dirent.h>
#include<stdio.h>
main()
{
//version 1
DIR *d;
struct dirent *de;
//Open a dir
d = opendir(".");
if(d == NULL)
{
printf("opendir error\n");
exit(-1);
}
//Loop the dir
while(de = readdir(d))
{
printf("%s----%d\n",de->d_name,de->d_type);
}
//close the dir
closedir(d);
//version 2
int myFilter(const struct dirent*d)
{
if(memcmp(d->d_name,".",1) == 0)
return 0;
else
return -1;
}
int mySort(const void* d1,const void* d2)
{
return -alphasort(d1,d2);
}
struct dirent **d;
int r;
int i;
r = scandir("/home",&d,myFilter,mySort);
printf("The number of subdirectores : %d\n",r);
//loop version 1
for(i = 0; i < r; i++)
{
printf("%s\n",d[i]->d_name);
}
//loop version 2
while(*d)
{
//printf("%s\n",(*d)->d_name);
d++;
}
}
posted on 2018-09-13 05:04 langjitianyadaolao 阅读(89) 评论(0) 编辑 收藏 举报