大家好 小弟似乎有一陣子沒來嘴砲了,先打完這篇,
晚點再來補篇最近的心得感想。
以下是 ls linux C程式碼
晚點再來補篇最近的心得感想。
以下是 ls linux C程式碼
1 #include
2 #include
3 #include
4 #include
5
6 int main(void)
7 {
8 char *curr_dir = NULL;
9 DIR *dp = NULL;
10 struct dirent *dptr = NULL;
11 unsigned int count = 0;
12
13 // Get the value of environment variable PWD
14 //curr_dir = getenv("PWD");
15 curr_dir = "/tmp/usbmounts";
16 if(NULL == curr_dir)
17 {
18 printf("\n ERROR : Could not get the working directory\n");
19 return -1;
20 }
21
22 // Open the current directory
23 dp = opendir((const char*)curr_dir);
24 if(NULL == dp)
25 {
26 printf("\n ERROR : Could not open the working directory\n");
27 return -1;
28 }
29
30 printf("\n");
31 // Go through and display all the names (files or folders)
32 // Contained in the directory.
33 for(count = 0; NULL != (dptr = readdir(dp)); count++)
34 {
35 //ignore "."& ".."
36 if(strcmp(dptr->d_name,".")==0 || strcmp(dptr->d_name,"..")==0)
37 continue;
38 if(2 == count)
39 printf("%s ",dptr->d_name);
40 }
41 //printf("\n %u\n", count-2);
42
43 return 0;
44 }
下面這段是 最近卡關的 ps,書本上的run 不起來,自己又改了一些,目前可以分析出/proc 資料夾內是數字的path,
在考慮該怎麼讀檔才對,因為用fopen 都會跳錯誤,說找不到檔案開啟,但我複製 印出來的位置 是存在的,
不確定是不是被結束字元那類的搞到?
1 #include
2 #include
3 #include
4 #include
5 #include
6 #include
7 #include
8 #include
9 #include
10
11 #define MAX 1024
12 #define PATH_SIZE 128
13
14
15 int main(void)
16 {
17 DIR *dir;
18 struct dirent *entry;
19 FILE *fp;
20 char path[PATH_SIZE];
21 char buf[MAX];
22 int k;
23
24 printf("NAME\tPID\n"); /*output head*/
25
26 if((dir = opendir("/proc")) == NULL){ /*open /proc dir*/
27 perror("fail to open dir");
28 return -1;
29 }
30
31 while((entry = readdir(dir)) != NULL){
32 if(strcmp(entry->d_name,".")==0 || strcmp(entry->d_name,"..")==0)
33 continue;
34
35 //printf("%s ",entry->d_name);
36 k = isdigit(entry->d_name[0]);
37 //printf("k = %d\n", k);
38 if(k > 0){
39 sprintf(path, "/proc/%s/task/%s/status", entry->d_name, entry->d_name);
40 //printf("%s", path);
41 }
以上
Thanks,
下台一鞠躬
留言