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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>

char *path_cat (const char *str1, char *str2);

int main () {
	struct dirent *dp;

        // enter existing path to directory below
	const char *dir_path="/path/to/directory/to/list";
	DIR *dir = opendir(dir_path);
	while ((dp=readdir(dir)) != NULL) {
		char *tmp;
		tmp = path_cat(dir_path, dp->d_name);
		printf("%s\n", tmp);
		free(tmp);
		tmp=NULL;
	}
	closedir(dir);
	return 0;
}

char *path_cat (const char *str1, char *str2) {
	size_t str1_len = strlen(str1);
	size_t str2_len = strlen(str2);
	char *result;
	result = malloc((str1_len+str2_len+1)*sizeof *result);
	strcpy (result,str1);
	int i,j;
	for(i=str1_len, j=0; ((i<(str1_len+str2_len)) && (j<str2_len));i++, j++) {
		result[i]=str2[j];
	}
	result[str1_len+str2_len]='\0';
	return result;
}

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

#include <sys/statvfs.h>
#include <glib.h>

gchar *
g_get_capacity ( gchar * dev_path)
{
	unsigned long long result = 0;
	int n;
	gchar s_cap[50];
	gchar * ss_cap = "N/A";
	struct statvfs sfs;
	if ( statvfs ( dev_path, &sfs) != -1 )
	{
		result = (unsigned long long)sfs.f_bsize * sfs.f_blocks;
	}
	if (result > 0)
	{
		double f_cap = (double)result/(1024*1024);
		n = sprintf(s_cap, "%.2f Mb", f_cap);
		ss_cap = g_strdup(s_cap);
	}
	return ss_cap;
}

gchar * 
g_get_free_space ( gchar * dev_path)
{
	unsigned long long result = 0;
	int n;
	gchar s_cap[50];
	gchar * ss_cap = "N/A";
	struct statvfs sfs;
	if ( statvfs ( dev_path, &sfs) != -1 )
	{
		result = (unsigned long long)sfs.f_bsize * sfs.f_bfree;
	}
	if (result > 0)
	{
		double f_cap = (double)result/(1024*1024);
		n = sprintf(s_cap, "%.2f Mb", f_cap);
		ss_cap = g_strdup(s_cap);
	}
	return ss_cap;
}
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS