You can read a row, then scan it to find the beginning of each column. Then use the column data, but you want to.
#include <stdio.h> #include <string.h> #include <ctype.h> #define MAX_COL 3 #define MAX_REC 512 int main (void) { FILE *input; char record[MAX_REC + 1]; char *scan; const char *recEnd; char *columns[MAX_COL] = { 0 }; int colCnt; input = fopen("input.txt", "r"); while (fgets(record, sizeof(record), input) != NULL) { memset(columns, 0, sizeof(columns)); // reset column start pointers scan = record; recEnd = record + strlen(record); for (colCnt = 0; colCnt < MAX_COL; colCnt++ ) { while (scan < recEnd && isspace(*scan)) { scan++; } // bypass whitespace if (scan == recEnd) { break; } columns[colCnt] = scan; // save column start while (scan < recEnd && !isspace(*scan)) { scan++; } // bypass column word *scan++ = '\0'; } if (colCnt > 0) { printf("%s", columns[0]); for (int i = 1; i < colCnt; i++) { printf("#%s", columns[i]); } printf("\n"); } } fclose(input); }
Please note that the code can still use some reliable identification: check for w / ferror file errors; ensure that eof is hit; provide a complete record (all column data). It can also be made more flexible by using a linked list instead of a fixed array and can be modified so as not to assume that each column contains only one word (provided that the columns are separated by a specific character).
source share