Unpredictable behaviour in simple loop to check if line & col exists in file

后端 未结 1 1510
粉色の甜心
粉色の甜心 2021-01-27 04:42

Below is the code for a function that checks if the line and column \'co-ordinates\' given to it are valid for a file whose pointer is passed to it.

12 hours of

相关标签:
1条回答
  • 2021-01-27 05:27

    The posted code has two problems.

    • if(f==0){ /* line was valid */ } does not reset i = 0 before the following while(i<line-1) loop. Because i == line-1 after the previous loop, the second while gets skipped altogether, and reading proceeds from the beginning of the file, instead of line line.

    • A line is not counted as complete until if(chk=='\n') evaluates to true. This skips over the last line in the file if it is not terminated with a \n newline. In the simplest case, a file with just one (non-empty) line but without a \n terminator will always fail the check_valid test.

    While each of those can be easily fixed, a more direct way is to do the checks in a single pass.

    while(i < line){
        chk = fgetc(ffind);
        if(chk == EOF){
            printf("\nInvalid %s.\n", (i == line - 1) ? "Column" : "Line"); break;
        }
        else if(chk == '\n'){
            if(i == line - 1){
                printf("\nInvalid Column.\n"); break;
            }
            i++; q = 0;
        }
        else if(i == line - 1 && q == col - 1){
            printf("\nValid Line/Column.\n"); break;
        }
        else
            q++;
    }
    
    0 讨论(0)
提交回复
热议问题