Switch and For Statements, Command Line and File Handling - Records and Fields

Chapter chap9 section 8

For many applications it is necessary, or useful, to regard the records of a file as consisting of a set of fields. The standard file handling functions provide no support for fields. There are two common approaches to splitting records into fields. The first approach, understood by many Unix utilities, is to designate a special character as the field separator character, this allows a variable number of variable width fields; the alternative is to define fields as being of a specific width.

When handling data organised into fields within records it is often useful to represent the record as a sequence of strings. The following program shows how this might be done.

#include	<stdio.h>
#define	MAXCHAR	120	/* maximum record size */
#define	MAXFLDS	20	/* maximum number of fields */
#define	SEPCHAR	':'	/* field separator */
main()
{
	char	ibf[MAXCHAR];	/* input buffer */
	char	*fields[MAXFLDS];  /* field pointers */
	int	i;
	int	j;
	int	nfields;	/* number of fields */
	while(gets(ibf)!=NULL)
	{
		fields[0] = ibf;
		i=0;
		for(j=0;ibf[j];)
		{
			if(ibf[j]==SEPCHAR)
			{
			      fields[++i] = &ibf[j+1];
			      ibf[j]='\0';
			}
			j++;
		}
		nfields = i+1;
		printf("%d fields\n",nfields);
		for(j=0;j<nfields;j++)
	       	   printf("field %2d >>%s<<\n",j,fields[j]);
	}
}
The program, which reads the data from its standard input, produced the following output
3 fields
field  0 >>a<<
field  1 >>b<<
field  2 >>c<<
1 fields
field  0 >>some data<<
2 fields
field  0 >><<
field  1 >>starts with a null field<<
2 fields
field  0 >>ends with a null field<<
field  1 >><<
when presented with the input
a:b:c
some data
:starts with a null field
ends with a null field:


Exercises