cfile

how to extract a string/char from a formatted file input using fscanf in C?


I'm trying to extract an operator from the input file using fscanf, operator being (+,-,*,/) which is located in this line "(C = (A[i] OP B[i]) + C) << 3;". How can i approach this?

FILE *file = fopen("project2Input.txt", "r");
if (file == NULL) {
    perror("Error opening file");
    return 1;
}
int k, N;
char op[3];
fscanf(file, "long myFunction(long A[], long B[], int k, int N) {");
fscanf(file, "long C;");
fscanf(file, "for (int i = %d; i < %d; i++){", &k, &N);
fscanf(file, "(C = (A[i] %2[-+*/] B[i]) + C) << 3;", op);
op[2] = '\0';
fscanf(file, "} return C;}");
fclose(file);
printf("op: %s\n", op);

//input file (project2Input.txt)
long myFunction(long A[], long B[], int k, int N) {
    long C;
    for (int i = k; i < N; i++){
        (C = (A[i] - B[i]) + C) << 3;
    }
    return C;
}

Solution

  • The operator string is one character long, so %2[-+*/] should be %1[-+*/] and char op[3]; can be changed to char op[2] = ""; to reduce its size and initialize it.

    %d will not match the 'k' and 'N' characters in the for loop. Maybe use %c to match them and change int k, N; to char k, N;.

    Optional white-space should be allowed between all C tokens. You can use a white-space character in the scanf format string wherever optional white-space is allowed.

    There needs to be mandatory white-space matching between some C tokens such as between long and myFunction, otherwise longMyfunction would be matched. C interprets the space, newline, form-feed, horizontal tab, and vertical tab characters as white-space. It also converts comments to white-space, but let us ignore the possibility of comments in the project2Input.txt file as it is tricky to deal with!

    #include <stdio.h>
    
    #define MWS "%*[ \f\n\t\v]" /* match mandatory white-space */
    
    int main(void) {
        FILE *file = fopen("project2Input.txt", "r");
        if (file == NULL) {
            perror("Error opening file");
            return 1;
        }
        char op[2] = "";
        char k, N;
        fscanf(file, " long" MWS "myFunction ( long" MWS "A [ ] , long" MWS
                     "B [ ] , int" MWS "k , int" MWS "N ) {");
        fscanf(file, " long" MWS "C ;");
        fscanf(file, " for ( int" MWS "i = %c ; i < %c ; i ++ ) {", &k, &N);
        fscanf(file, " ( C = ( A [ i ] %1[-+*/] B [ i ] ) + C ) << 3 ;", op);
        fscanf(file, " } return" MWS "C ; }");
        fclose(file);
        printf("op: %s\n", op);
    }