#include #include // Primitive File Parsing. // // This code demonstrates some of the less familiar features of sscanf that are // useful for file parsing. The program reads and prints how many ints are // there per line in a given text file. int main() { FILE *fp; int a, num, count; char BUFFER[1024]; if( (fp = fopen("numbers.txt", "r")) == NULL) { printf("File not found!\n"); return -1; // exit the program here } while (fgets(BUFFER, 1024, fp) != NULL ) // read one line into BUFFER (up to 1024 character max) { int idx=0; int k=0; do { num = sscanf( &(BUFFER[idx]), "%d%n", &a, &count); // num should be 1 if everythign was read OK // %n does not read anyting from the string but // it stores the number of characters read in count. if(num == 1) { printf("%d, ", a); idx+=count; // advance the index into BUFFER for the next call to sscanf k++; } } while(num != EOF); printf("[%d ints on this line]\n", k); } fclose(fp); system("pause"); }