I wouldn't recommend using %s
unless you can guarantee that the fields won't contain embedded whitespace. Further, you should always use a field width for string specifiers in scanf
to avoid buffer overflow.
Ignoring the possibility of quoted fields that contain embedded tabs, it's straightforward to read a line with fgets
and then parse it with sscanf
:
#include <stdio.h>
int main(void)
{
FILE *in = fopen("input.txt", "r");
if (in != NULL)
{
char line[1024];
while (fgets(line, sizeof line, in) != NULL)
{
char field[1024];
int offset = 0;
// Break down the line based on tabs ('\n' included because fgets retains a newline if it's present)
while (sscanf(line + offset, "%1023[^\t\n]", field) == 1)
{
puts(field);
offset += strlen(field);
// Safety check to avoid stepping off the end of the array
if (line[offset] != '\0')
{
++offset;
}
}
}
fclose(in);
}
return 0;
}
Note the use of a scanset in scanf
to look explicitly for tabs.