[Solved] Reading file character by character, line by line in C


Obviously I can’t use your exact code, or you would not have asked the question, but this is a similar idea, done a bit differently, and also using the fgets which was causing you trouble. It works by searching each line for digits, and non-digits. Note that I have #define MAXLEN 2000 to be generous, because in the previous question, you say each number can have 500 digits, so the line might be at least 1000 characters.

#include <stdio.h>
#include <ctype.h>

#define MAXLEN  2000

int main(void)
{
    FILE *fp;
    char line[MAXLEN];
    char *ptr;
    if((fp = fopen("test.txt", "rt")) == NULL)
        return 0;                               // or other action

    while(fgets(line, MAXLEN, fp) != NULL) {
        ptr = line;
        // first number
        while(*ptr && !isdigit(*ptr)) {        // skip non-digits
            ptr++;
        }
        while(*ptr && isdigit(*ptr)) {
            printf("%c", *ptr++);              // print digits
        }
        printf(" ");

        // second number
        while(*ptr && !isdigit(*ptr)) {        // skip non-digits
            ptr++;
        }
        while(*ptr && isdigit(*ptr)) {
            printf("%c", *ptr++);              // print digits
        }
        printf("\n");

    }
    fclose(fp);
    return 0;
}

EDIT you could make it more concise like this, with a loop to read each set of digits:

char *terminate = " \n";                    // 1st number ends with space, 2nd with newline
int i;
while(fgets(line, MAXLEN, fp) != NULL) {
    ptr = line;
    for(i=0; i<2; i++) {
        while(*ptr && !isdigit(*ptr)) {     // skip non-digits
            ptr++;
        }
        while(*ptr && isdigit(*ptr)) {
            printf("%c", *ptr++);           // print digits
        }
        printf("%c", terminate[i]);         // space or newline
    }
}

Program output (from your input):

10 5003
20 320
4003 200

solved Reading file character by character, line by line in C