cfile

Ignoring \n when reading from a file in C?


I was wondering if it is possible to ignore the new lines when reading a file. I've written a little program that reads the characters from a file and formats them but the new lines in the document mess up the formatting, I end up with double spaces where I only want a single spacing.

Is it possible to disable this feature? So that the only new lines my program prints out are the new lines that I insert into the print functions in my program?


Solution

  • C doesn't provide much in the way of conveniences, you have to provide them all yourself or use a 3rd party library such as GLib. If you're new to C, get used to it. You're working very close to the bare metal silicon.

    Generally you read a file line by line with fgets(), or my preference POSIX getline(), and strip the final newline off yourself by looking at the last index and replacing it with a null if it's a newline.

    #include <string.h>
    #include <stdio.h>
    
    char *line = NULL;
    size_t line_capacity = 0; /* getline() will allocate line memory */
    
    while( getline( &line, &line_capacity, fp ) > 0 ) {
        size_t last_idx = strlen(line) - 1;
    
        if( line[last_idx] == '\n' ) {
            line[last_idx] = '\0';
        }
    
        /* No double newline */
        puts(line);
    }
    

    You can put this into a little function for convenience. In many languages it's referred to as chomp.

    #include <stdbool.h>
    #include <string.h>
    
    bool chomp( char *str ) {
        size_t len = strlen(str);
    
        /* Empty string */
        if( len == 0 ) {
            return false;
        }
    
        size_t last_idx = len - 1;
        if( str[last_idx] == '\n' ) {
            srt[last_idx] = '\0';
            return true;
        }
        else {
            return false;
        }
    }
    

    It will be educational for you to implement fgets and getline yourself to understand how reading lines from a file actually works.