C language: split lines by tabs (strsep() and fgets() usage)

Subject: show how to split lines by tabs using strsep() and fgets() function calls in C-language (C99).

Usage: compile source C-code with GCC (M$ Visual Studio does not support strsep() function call)

and run it with one option: the name of file (like <the name of program> <the name of file>).

//------- the start of the C code -------

/********************************************************************* * Author: Stepan A. Baranov (rosmir@gmail.com) * web-site: www.rosmir.org *********************************************************************/ #include <stdio.h> #include <limits.h> #include <string.h> #define B_S 1 #define G_S 0 int main (int argc, const char *argv[]) { int i = 1, j = 1; char line[LINE_MAX], *templine, *linePtr; FILE *fp; fp = fopen (argv[1], "rb"); if (fp == NULL) return B_S; fseek (fp, 0, SEEK_SET); while (fgets (line, LINE_MAX, fp) != NULL) { printf ("line %i: %s", i++, line); linePtr = line; linePtr = strsep (&linePtr, "\n"); while ((templine = strsep (&linePtr, "\t")) != NULL) printf ("(%i: %s) ", j++, templine); printf ("\n"); j = 1; } return G_S; }

//------- the end of the C code -------

©2009 Rosmir - Stepan A. Baranov

$Id: strsep-fgets.html 413 2009-01-06 21:16:05Z rosmir $