João Vieira
João Vieira

Reputation: 121

How to read properly from a file

Hello! I'm trying to solve the Longest Common Subsequence problem and i'm crashing on a problem that has nothing to do with the problem itself. I dont think my program isnt showing the right final result because its not reading properly both sequences

The code of the main function where I read the the sequences from one single file(first line is the first sequence, second line is the second sequence) and is here where I believe the error is.

int main(){
    FILE *file;
    char c;
    int m=0, n=0, flag=0;
    file=fopen("test.txt","r");
    if(file==NULL){
        printf("Error opening file.\n");
        exit(0);
    }

    if(file){
        while((c=fgetc(file))!=EOF){
            if(c!=' ' && c!='\n' && flag==0)
                m++;
            if(c=='\n')
                flag=1;
            if(c!=' ' && c!='\n' && flag==1)
                n++;
        }
    }

    char X[m], Y[n];
    int i=0;

    if(file){
        while((c=fgetc(file))!=EOF){
            if(c!=' ' && c!='\n' && flag==0){
                i++;
                X[i]=c;
            }
            if(c=='\n'){
                flag=1;
                i=0;
            }               
            if(c!=' ' && c!='\n' && flag==1)
                i++;
                Y[i]=c;
        }
    }
    int j;
    for(i=0;i<m;i++){
            printf("%c | %c",X[i],Y[i]);

    }



    printf("Length of LCS is %d .\n", lcs( X, Y, m, n ) );

    return 0;
}

this is what it returns when im printing the first sequence. 7 | É | Û | © | È | ³ | | |

Sorry for the long post. Thank you in advance for anyone willing to help

Upvotes: 0

Views: 31

Answers (1)

AlexP
AlexP

Reputation: 4430

The first while loop consumes all the contents of the file, because it runs until fgetc() returns EOF. The second while loop does not run at all, because the file has been exhausted. The arrays X[] and Y[] remain uninitialised.

Not to mention that once you have handled the case file == NULL there is no need to check whether it has magically become NULL -- the if (file) statements are useless.

Upvotes: 2

Related Questions