Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Tvrtko remind-nix.blogspot.com

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Listing the files and subdirectories in C - Linux

// program lists the files and subdirectories within a given directory in full path

   1  
   2  #include <stdio.h>
   3  #include <stdlib.h>
   4  #include <string.h>
   5  #include <dirent.h>
   6  
   7  char *path_cat (const char *str1, char *str2);
   8  
   9  int main () {
  10  	struct dirent *dp;
  11  
  12          // enter existing path to directory below
  13  	const char *dir_path="/path/to/directory/to/list";
  14  	DIR *dir = opendir(dir_path);
  15  	while ((dp=readdir(dir)) != NULL) {
  16  		char *tmp;
  17  		tmp = path_cat(dir_path, dp->d_name);
  18  		printf("%s\n", tmp);
  19  		free(tmp);
  20  		tmp=NULL;
  21  	}
  22  	closedir(dir);
  23  	return 0;
  24  }
  25  
  26  char *path_cat (const char *str1, char *str2) {
  27  	size_t str1_len = strlen(str1);
  28  	size_t str2_len = strlen(str2);
  29  	char *result;
  30  	result = malloc((str1_len+str2_len+1)*sizeof *result);
  31  	strcpy (result,str1);
  32  	int i,j;
  33  	for(i=str1_len, j=0; ((i<(str1_len+str2_len)) && (j<str2_len));i++, j++) {
  34  		result[i]=str2[j];
  35  	}
  36  	result[str1_len+str2_len]='\0';
  37  	return result;
  38  }

C functions for getting disk space information in Linux OS

These are 2 C functions for getting disk capacity and disk free space in megabytes into char array

   1  
   2  #include <sys/statvfs.h>
   3  #include <glib.h>
   4  
   5  gchar *
   6  g_get_capacity ( gchar * dev_path)
   7  {
   8  	unsigned long long result = 0;
   9  	int n;
  10  	gchar s_cap[50];
  11  	gchar * ss_cap = "N/A";
  12  	struct statvfs sfs;
  13  	if ( statvfs ( dev_path, &sfs) != -1 )
  14  	{
  15  		result = (unsigned long long)sfs.f_bsize * sfs.f_blocks;
  16  	}
  17  	if (result > 0)
  18  	{
  19  		double f_cap = (double)result/(1024*1024);
  20  		n = sprintf(s_cap, "%.2f Mb", f_cap);
  21  		ss_cap = g_strdup(s_cap);
  22  	}
  23  	return ss_cap;
  24  }
  25  
  26  gchar * 
  27  g_get_free_space ( gchar * dev_path)
  28  {
  29  	unsigned long long result = 0;
  30  	int n;
  31  	gchar s_cap[50];
  32  	gchar * ss_cap = "N/A";
  33  	struct statvfs sfs;
  34  	if ( statvfs ( dev_path, &sfs) != -1 )
  35  	{
  36  		result = (unsigned long long)sfs.f_bsize * sfs.f_bfree;
  37  	}
  38  	if (result > 0)
  39  	{
  40  		double f_cap = (double)result/(1024*1024);
  41  		n = sprintf(s_cap, "%.2f Mb", f_cap);
  42  		ss_cap = g_strdup(s_cap);
  43  	}
  44  	return ss_cap;
  45  }
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS