歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Unix知識 >> Unix教程 >> 高手進階:UNIX系統環境下高級編程一例

高手進階:UNIX系統環境下高級編程一例

日期:2017/2/27 17:40:01   编辑:Unix教程
  最近在看著本書,感覺不錯,今天先拿第一個程序練練,這是打印一個文件下的文件的程序,是第一個程序,比較簡單,代碼如下:

#include "err.h"
#include <dirent.h>
int main(int argc, char* argv[])
{
  DIR *dp;
  struct dirent *dirp;

  if(argc != 2)
    err_quit("usage: ls directory_name");

  if((dp = opendir(argv[1])) == NULL)
     err_sys("Can't open %s", argv[1]);
  while((dirp = readdir(dp)) != NULL)
    printf("%s\n", dirp->d_name);

  close(dp);
  return 0;
}

這裡用到的err.h是一個自己編寫的頭文件,因為這本書中用到的源文件都早apue上,我自己寫了一部分,這個err_quit其中應該是變參數的,但是我還不會寫,明天看看,現在太晚了,頭文件如下:

#include <stdio.h>
void err_quit(const char *fmt)
{
  printf( "%s\n", fmt);
  
}

void err_sys(const char *f, const char *s)
{
  printf("%s %s\n", f, s);
}

打印一個輸出結果如下:

[root@localhost apue]# ./a.out .
.
..
apue
apue.h
rk1.c~
err.h
a.out
fig1.3.c
rk1.c

這個程序有很多需要注意的地方,雖然代碼很少,但是很典型。

Copyright © Linux教程網 All Rights Reserved