code vault - readlineWhat links here?
This function reads one line of characters from the given file and stores them in the character array provided by the caller.

The function tests for end of file (feof), and operating system errors on read (ferror). If either condition occurs, a 0 is returned to indicate the failure.

Arguments



Return

Returns 0 on failure, 1 on success.

Notes

This may leave a dangling CR or LF as the first character to be read next time. That's why it ignores empty lines.

Code

//##############################################################################
// read one line from the specified file.  the newline char is discarded
// return 0 on failure, 1 on success
//##############################################################################
int readline(FILE *file, char *line, int max)
{
    int  i = 0;
    
    while(i < max - 1) {
        char result = fgetc(file);
        if (feof(file) || ferror(file)) return (0);
        if (i == 0 && result == '\n') continue;
        if (i == 0 && result == '\r') continue;
        if (result == '\n') break;
        if (result == '\r') break;
        line[i++] = result;
    }
    line[i] = '\0';
    return (1);
}


Typical Usage

    if (infile) {
        char    line[1001];
        
        while (readline(infile, line, 1000)) {
            printf("%s\n", line);
        }
        fclose(infile);
    }
code vault - readline
programming - c - time related
programming - C - function putc(int char, FILE* stream)
programming - C - functions for searching for files
filename:code vault - readline
filename:code%20vault%20%2D%20readline
last edit:March 26 2009 19:55:40 (5828 days ago)
ct = 1741678853.000000 = March 11 2025 03:40:53
ft = 1238111740.000000 = March 26 2009 19:55:40
dt = 503567113.000000