Search code examples
cfgets

Given a filename in C how to read each line for only 75 characters?


Suppose I have a file that contains the contents below:

This line contains more than 75 characters due to the fact that I have made it that long. 
Testingstring1
testingstring2

This is my code:

void checkLine( char const fileName[]){
    FILE *fp = fopen(fileName,"r");
    char line[75];
    while (1) {
        fgets(line,75,fp);
        if (feof(fp)){
            break;
        } else {
            printf("%s\n", line);
        }
    }
}

How do I make it so that it only saves the first 75 characters from each line in the variable line?

The code above gives the following output:

This line contains more than 75 characters due to the fact that I have mad
e it that long.

Testingstring1

testingstring2

The expected output is supposed to be like this:

This line contains more than 75 characters due to the fact that I have mad
Teststring1
Teststring2

Solution

  • The maximal strlen will be 74.

    bool prior_line_ended = true;
    while (1) {
        fgets(line, 75, fp);
        if (feof(fp)){
            break;
        }
    
        // Remove any line end:
    
        char* pos = strchr(line, '\n');
        //char* pos = strchr(line, '\r');
        //if (pos == NULL) {
        //    pos = strchr(line, '\n');
        //}
        bool line_ended = pos != NULL;
        if (line_ended) {
            *pos = '\0';
        }
    
        // Output when starting fresh line:
    
        if (prior_line_ended) {
            printf("%s\n", line);
        }
        prior_line_ended = line_ended;
    }