Write a small program in C language to obtain Linux local directory and local information, and obtain information examples such as system memory, cpu, hard disk, etc.

Applets that display directories
Show applets that specify directories:
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
# include <stdlib.h>
  
void printdir(char *dir,int depth){   DIR *dp;   struct dirent *entry;   struct stat statbuf;   if((dp = opendir(dir)) == NULL){     fprintf(stderr, " cannot open directory: %s\n", dir);     return;   }   chdir(dir);   while((entry = readdir(dp)) != NULL){     lstat(entry->d_name,&statbuf);     if(S_ISDIR( statbuf.st_mode)){       /*Found a directory, but ignore . and ..*/



  




  





      if(strcmp(".",entry->d_name) == 0 || strcmp("..",entry->d_name) == 0){
        continue;
      }
      printf("%*s%s/ \n",depth,"",entry->d_name);
      /*Recurse at a new indent level*/
      printdir(entry->d_name,depth+4);
    }else{
      printf("%*s%s \n",depth,"",entry->d_name);
    }
  
  }
}
int main(){
  /*
  show directory
  */
  printf("Directory scan of /home:\n");
  printdir("/home",0);
  printf("done. \n");
    
  exit(0);
}
根据参数输出目录的结构
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
  
void printdir(char *dir,int depth){
  DIR *dp;
  struct dirent *entry;
  struct stat statbuf;
  
  if((dp = opendir(dir)) == NULL){
    fprintf(stderr, "cannot open directory: %s\n", dir);
    return;
  }
  
  chdir(dir);
  while((entry = readdir(dp)) != NULL){
    lstat(entry->d_name,&statbuf);
    if(S_ISDIR(statbuf.st_mode)){
      /*Found a directory,but ignore . and ..*/
      if(strcmp(".",entry->d_name) == 0 || strcmp("..",entry->d_name) == 0){
        continue;
      }
      printf("%*s%s/ \n",depth,"",entry->d_name); /
      *Recurse at a new indent level*/
      printdir(entry->d_name,depth+4);
    }else{       printf ("%*s%s \n",depth,"",entry->d_name); } } }     int   main ( int argc, char* argv[]){   /*   show directory   */   char *topdir = ". ";   if(argc >= 2){     topdir = argv[1];   }   printf("Directory scan of %s:\n",topdir);   printdir(topdir,0);   printf("done.\n") ;   exit(0); } Get basic host information Get host user information: #include <sys/types.h> #include <pwd.h> #include <stdio.h>


  













    







#include <unistd.h>
  
int main(){
  uid_t uid;
  gid_t gid;
  
  struct passwd *pw;
  uid = getuid();
  gid = getgid();
  
  printf("User is %s\n",getlogin());
  
  printf("User IDs: uid=%d, gid=%d \n", uid, gid);
  
  pw = getpwuid(uid);
  printf("UID passwd entry: \n name=%s, uid=%d, gid=%d, home=%s, shell=%s\n",pw->pw_name, pw->pw_uid, pw->pw_gid, pw->pw_dir, pw->pw_shell);
  
  pw = getpwnam("root");
  printf("root passwd entry: \n");
  printf("name=%s, uid=%d, gid=%d, home=%s, shell=%s \n",pw->pw_name, pw->pw_uid, pw->pw_gid, pw->pw_dir, pw->pw_shell);
  exit(0);
}
获取主机自身信息:
#include <sys/utsname.h>
#include <unistd.h>
#include <stdio.h>
  
  
int main(){
  char computer[256];
  struct utsname uts;
  if(gethostname(computer, 255) != 0 || uname(&uts) < 0){
    fprintf(stderr, "Could not get host information \n");
    exit(1);
  }
  
  printf("Computer host name is %s \n",computer);
  printf("System is %s on %s hardware \n",uts.sysname, uts.machine);
  printf("Nodename is %s \n",uts.nodename);
  printf("Version is %s , %s \n",uts.release, uts.version);
  
  exit(0);
}
#include <sys/utsname.h>
#include <unistd.h>
#include <stdio.h>
 
 
int main(){
  char computer[256];
  struct utsname uts;
  if(gethostname(computer, 255) != 0 || uname(&uts) < 0){
    fprintf(stderr, "Could not get host information \n");
    exit(1);
  }
 
  printf("Computer host name is %s \n",computer);
  printf("System is %s on %s hardware \n",uts.sysname, uts.machine);
  printf("Nodename is %s \n",uts.nodename);
  printf("Version is %s , %s \n",uts.release, uts.version);
 
  exit(0);
}

Get system memory, cpu, hard disk and other information

 #include <stdio.h>
 #include <sys/time.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <unistd.h>
 #include <fcntl.h>
 #include <stdlib.h>
 #include <string.h>
 void sampleLoadAvg(){     int f=0;     char buffer[80]="";                     /* 定义字符串并初始化为'\0' */     char buf[5][10];     char *file="/proc/loadavg";     f = open(file, O_RDONLY);     if (f == 0)     {         printf("error to open: %s\n", file);         exit(EXIT_FAILURE);     }     read(f, (void *)buffer, 80);     sscanf(buffer, "%s %s %s %s %s", /* sscanf() split into multiple strings*/












           &buf[0],&buf[1],&buf[2],&buf[3],&buf[4]); printf("One minute average load: %s\n", buf[0]); printf(
    "
    5 Minute average load: %s\n", buf[1]);
    printf("A quarter of an hour average load: %s\n", buf[2]);
    printf("Sampling time interval: %s\n", buf[3]);
    printf("The maximum number of threads: %s\n", buf[4]);
    close(f);
 }
 void sampleTime(){     int f=0;     char buffer[80]="" ;     char buf[2][10];     float seconds=0;     float secondr=0;     char *file="/proc/uptime";     f = open(file, O_RDONLY);     if (f == 0)     {         printf( "error to open: %s\n", file);         exit(EXIT_FAILURE);     }     read(f, (void *)buffer, 80);













    sscanf(buffer, "%s %s", &buf[0], &buf[1]);
    close(f);
    printf("System running time: \t%s seconds\n", buf[0]);
    printf ("System idle time: \t%s seconds\n", buf[1]);
    close(f);
    seconds=strtof(buf[0],NULL);
    secondr=strtof(buf[1],NULL);
    printf("System running time:\t%03dday%02dhour%02dminute%02.6fsecond\n", 
           (int)seconds/(24*3600), /*day*/
           ((int)seconds/(3600 ))%(24), /* hours*/
           ((int)seconds/60)%60, /* minutes*/
           ((int)seconds%60)+(seconds-(int)seconds)); /* seconds (accurate to milliseconds) */
    printf("System idle time: \t%03d days %02d hours %02d minutes %02.6f seconds\n", ( 
           int)secondr/(24*3600), /* days*/
           ( (int)secondr/(3600))%(24),/* hour*/
           ((int)secondr/60)%60, /* minute*/
           ((int)secondr%60)+(secondr-(int)secondr)); /* second (accurate to millisecond) */ }
 void
 
 sampleKernelVersion() {     int f=0;     char buffer[80]="";     char *file="/proc/sys/kernel/version";     f = open(file, O_RDONLY);     if (f == 0)     {         printf(" error to open: %s\n", file);         exit(EXIT_FAILURE);     }     read(f, (void *)buffer, 80);     buffer[strlen(buffer)-1]=0; /* Simple implementation of tr( ) function */     printf("current kernel version:\t%s\n", buffer);     close(f);  }  void sampleOsRelease(){     int f=0;














 


    char buffer[80]="";
    char *file="/proc/sys/kernel/osrelease";
    f = open(file, O_RDONLY);
    if (f == 0)
    {
        printf("error to open: %s\n", file);
        exit(EXIT_FAILURE);
    }
    read(f, (void *)buffer, 80);
    buffer[strlen(buffer)-1]=0;
    printf("当前发行版本:\t%s\n", buffer);
    close(f);
 }
 
 void sampleOsType(){
    int f=0;
    char buffer[80]="";
    char *file="/proc/sys/kernel/ostype";
    f = open(file, O_RDONLY);
    if (f == 0)
    {
        printf("error to open: %s\n", file);
        exit(EXIT_FAILURE);
    }
    read(f, (void *)buffer, 80);
    buffer[strlen(buffer)-1]=0;
    printf("Current operating system:\t%s\n", buffer);
    close(f);
 }
 
 void sampleDiskStat(){     int i;     FILE *fp;     int nread=0;     ssize_t len ​​= 0;     char *buffer=NULL;     char buf[20][32];     char *file="/proc/diskstats";     char *p ;     fp = fopen(file, "rb");     if (fp == NULL)     {         printf("error to open: %s\n", file);         exit(EXIT_FAILURE);     }     printf(" Disk read and write times \n");     while((nread = getline(&buffer, &len, fp)) != -1) { /* simply realize the function of reading lines*/
















        sscanf(buffer, "%04s%08s%s %s %s %s %s %s %s %s %s %s %s %s", 
              &buf[0],&buf[1],&buf[2],&buf[3],&buf[4],&buf[5],&buf[6],
              &buf[7],&buf[8],&buf[9],&buf[10],&buf[11],&buf[12],&buf[13]);
        if ((p=strstr(buf[2], "loop"))!=NULL)
        {
           ;                              /* loop本地回路不作操作 */
        }
        else {
           printf("%06s%08s%08s\n", 
                  &buf[2],&buf[3], &buf[7]);
        }
    }
 }
 
 void sampleProcesses(void)
 {
    FILE *fp;
    int nread=0;
    ssize_t len = 0;
    char *buf=NULL;
    char *buffer=NULL;
    char *file="/proc/stat";
    fp = fopen(file, "rb");
    if (fp == NULL)
    {         printf("error to open: %s\n", file);         exit(EXIT_FAILURE) ;     }     while((nread = getline(&buffer, &len, fp)) != -1) {         if((buf=strstr(buffer, "processes"))!=NULL) /* simply realize the function of grep*/            break ;     }     buffer[strlen(buffer)-1]=0; /* Simple implementation of tr() function*/     char count[16]="";     sscanf(buffer, "%s%s", count, count) ;     printf("Number of execution threads:\t%s\n", count);  }  void sampleContext(void)  {     FILE *fp;     int nread=0;     ssize_t len = 0;












 





    char *buf=NULL;
    char *buffer=NULL;
    char *file="/proc/stat";
    fp = fopen(file, "rb");
    if (fp == NULL)
    {         printf("error to open: % s\n", file);         exit(EXIT_FAILURE);     }     while((nread = getline(&buffer, &len, fp)) != -1) {         if((buf=strstr(buffer, "ctxt"))!= NULL) /* Simple implementation of grep function */            break;     }     buffer[strlen(buffer)-1]=0; /* Simple implementation of tr() function */     char count[16]="";     sscanf(buffer , "%s%s", count, count);     printf("Number of context switches:\t%s\n", count);  }  void sampleMeminfo()  {     FILE *fp;












 



    int nread=0;
    ssize_t len ​​= 0;
    char *buf=NULL;
    char *buffer=NULL;
    char *file="/proc/meminfo";
    char content[16]="";
    fp = fopen(file, "rb ");
    if (fp == NULL)
    {         printf("error to open: %s\n", file);         exit(EXIT_FAILURE);     }     while((nread = getline(&buffer, &len, fp)) != - 1) {         if((buf=strstr(buffer, "MemTotal"))!=NULL) /* Simple implementation of grep function */ {         buffer            [strlen(buffer)-1]=0; /* Simple implementation of tr() The function of the function */            sscanf(buffer, "%s%s", content, content);            int memtotal_kb=(int)(strtof(content,NULL));









           printf("Total memory capacity:\t%dG%4dM %4dK\n",
                  memtotal_kb/(1024*1024), /* Gb */
                  (memtotal_kb/(1024))%1024, /* Mb */
                  (memtotal_kb% (1024*1024))%1024); /* Kb */
        }
        if((buf=strstr(buffer, "MemFree"))!=NULL) /* simple grep function*/ {
        buffer            [strlen(buffer) -1]=0; /* Simple implementation of tr() function*/            sscanf(buffer, "%s%s", content, content);            int memfree_kb=(int)(strtof(content, NULL));            printf ("Memory available capacity:\t%dG%4dM %4dK\n",                   memfree_kb/(1024*1024), /* Gb */                   (memfree_kb/(1024))%1024, /* Mb */






                  (memfree_kb%(1024*1024))%1024); /* Kb */
        }
        if((buf=strstr(buffer, "SwapTotal"))!=NULL) /* simply realize the function of grep*/ {
        buffer            [strlen (buffer)-1]=0; /* Simple implementation of tr() function*/            sscanf(buffer, "%s%s", content, content);            int swaptotal_kb=(int)(strtof(content, NULL) );            printf("Total SWAP capacity:\t%dG%4dM %4dK\n",                   swaptotal_kb/(1024*1024), /* Gb */                   (swaptotal_kb/(1024))%1024, /* Mb */                   ( swaptotal_kb%(1024*1024))%1024); /* Kb */         }         if((buf=strstr(buffer, "SwapFree"))!=NULL) /* simply realize the function of grep*/         {










           buffer[strlen(buffer)-1]=0; /* Simple implementation of tr() function */
           sscanf(buffer, "%s%s", content, content);
           int swapfree_kb=(int)(strtof(content , NULL));
           printf("SWAP available capacity:\t%dG%4dM %4dK\n",
                  swapfree_kb/(1024*1024), /* Gb */
                  (swapfree_kb/(1024))%1024, /* Mb */
                  (swapfree_kb%(1024*1024))%1024); /* Kb */
           break; /* The required information has been satisfied, exit the loop */
        }
    }
 }
 /* 
  * === FUNCTION ===== ==================================================== ================
  * Name: main
  * Description:  
  * ==================================================== =========================================
  */
 int main ( int argc, char *argv[] )
 {     printf(">>>System Load<<<\n");     sampleLoadAvg();     printf("-------------------------- --------------\n");     printf("\n");     printf(">>>runtime<<<\n");     sampleTime();     printf(" \n");     printf(">>>Version Information<<<\n");     sampleOsType();     sampleOsRelease();     sampleKernelVersion();     printf("------------- --------------------------\n");     printf("\n");     printf(">>>Disk information<<<\n");     sampleDiskStat();















    printf("----------------------------------------\n");
    printf( "\n");
    printf(">>>Context switching<<<\n");
    sampleContext();
    printf("--------------------- -------------------\n");
    printf("\n");
    printf(">>>thread number<<<\n");
    sampleProcesses( );
    printf("-------------------------------------------\n");
    printf("\n");
    printf(">>>Memory Information<<<\n");
    sampleMeminfo();
    printf("------------------- ---------------------\n");
    return EXIT_SUCCESS;
 }

 

Guess you like

Origin blog.csdn.net/u010258235/article/details/116298784