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;
}

Put mounted drives list into Glist

Function that gets list of mounted drives from '/etc/fstab' and '/etc/mtab' files and puts data in the GList object (from GLib library) that can be further used in GTK.

#include <glib.h>
#include <mntent.h>
#include <string.h>

GList * g_get_drives_list(GList * g) {
	FILE *fstab = NULL;
	struct mntent *part = NULL;
	gchar *mntp = NULL;
	
	if ((fstab = setmntent( "/etc/fstab", "r" )) != NULL) {
		while ((part = getmntent(fstab))  != NULL) {
			if((strcmp(part->mnt_type, "proc")) != 0 && (strcmp(part->mnt_type, "devpts")) != 0 
																					&& (strcmp(part->mnt_type, "swap")) != 0) {
				mntp = g_strdup(part->mnt_dir);
				g=g_list_append(g, mntp);
			}
		}
		endmntent(fstab);
	}
	
	if ((fstab = setmntent( "/etc/mtab", "r")) != NULL) {
		while ((part = getmntent(fstab)) != NULL) {
			if (part->mnt_type != NULL) {
				if((strcmp(part->mnt_type, "proc")) != 0 && (strcmp(part->mnt_type, "devpts")) != 0
						&& (strcmp(part->mnt_type, "swap")) != 0 && (strcmp(part->mnt_type, "sysfs")) != 0
						&& (strcmp(part->mnt_type, "tmpfs")) != 0 && (strcmp(part->mnt_type, "fuseblk")) != 0
						&& (strcmp(part->mnt_type, "securityfs")) != 0) {
					if((g_list_find_custom(g, part->mnt_dir, (GCompareFunc)strcmp)) == 0) {
						mntp=g_strdup(part->mnt_dir);
						g=g_list_append(g, mntp);
					}
				}
			}
		}
		endmntent(fstab);
	}
	return g;
}
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS