Your problem can be solved with sscanf (with getline support), as shown below:
#include <stdio.h> #include <stdlib.h> int main(void) { FILE *fp; char *line = NULL; size_t len = 0; ssize_t read; /* tokens bags */ char tok_str[255]; int tok_int; fp = fopen("./file.txt", "r"); if (fp == NULL) exit(EXIT_FAILURE); /* Reads the line from the stream. */ while ((read = getline(&line, &len, fp)) != -1) { /* Scans the character string pointed by line, according to given format. */ sscanf(line, "%d\t%s", &tok_int, tok_str); printf("%d-%s\n", tok_int, tok_str); } if (line) free(line); exit(EXIT_SUCCESS); }
Or, even easier. You can use fscanf (with feof support) and replace the while loop shown above (along with some other redundant code cleanups) with the following:
while (!feof(fp)) { fscanf(fp,"%d\t%s\n",&tok_int, tok_str); printf("%d-%s\n", tok_int, tok_str); }
Assuming your file contains the following lines (where the format of one line is the number [tab] string [newline]):
12 apple 17 frog 20 grass
the output will be:
12-apple 17-frog 20-grass
source share