how to grab text w/ fcanf

Polytropon freebsd at
Fri Aug 1 00:00:28 UTC 2014

On Thu, 31 Jul 2014 16:33:35 -0700, Gary Kline wrote:
> 	I've got a *.c file that returns in [let's say]
> 		/tmp/share/voice
> 	a bunch of files named:  "text.1.txt", "text.2.txt",
> 	"text.3.txt" ... text.N-1.txt", each file containing a few
> 	sentences of plain ol' ASCII or [whatever] text.
> 	what is the easiest way, in C, *knowing the count=N*, to
> 	grab the *text files and stuff the paragraphs into a global
> 	buffer:	char *parabuffer[1024]; ??

I think scandir() is what you're searching for, in combination
with alphasort() to get the "natural" ordering of the files.
Plain C.

Example code:

	#include <dirent.h>
	#include <stdio.h>
	#include <stdlib.h>
	struct dirent **namelist;
	int i,n;

	    n = scandir(".", &namelist, 0, alphasort);
	    if (n < 0)
	    else {
	        for (i = 0; i < n; i++) {
	            printf("%s\n", namelist[i]->d_name);

Source for example:

You can iterate over namelist[] and access the d_name structure
member for the file name, and then use string operations like
strlcmp() or strnstr() to check for desired entries (given a
file mask, such as "test.*.txt", as a pattern).

See "man scandir" for details. Maybe consider readdir(),
see "man readdir" which contains the following example:

	len = strlen(name);
	dirp = opendir(".");
	while ((dp = readdir(dirp)) != NULL)
		if (dp->d_namlen == len && !strcmp(dp->d_name, name)) {
			return FOUND;
	return NOT_FOUND;

If this is too complicated, you could do the following, but
know that it's quick and _very_ dirty: sprintf() the filenames
with a counter N in the _known_ (!) pattern and test if the
files do exist, with fopen(); if fopen() fails, you know
that no further files will follow, you decrease the counter
by 1 and have the last valid index. :-)

As I initially said, this is quite low level C. Maybe you can
see something more elegant in the Gtk 3 documentation? But if
it has to be C, the suggested solutions are possible.

Magdeburg, Germany
Happy FreeBSD user since 4.0
Andra moi ennepe, Mousa, ...

More information about the freebsd-questions mailing list