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
Machines
materials
HOA
Government
care:programming
ubuntu
software - blender
Automobiles
filename:code vault - readline
filename:code%20vault%20%2D%20readline
last edit:March 26 2009 19:55:40 (6239 days ago)
ct = 1777164915.000000 = April 25 2026 20:55:15
ft = 1238111740.000000 = March 26 2009 19:55:40
dt = 539053175.000000