C read file line by line

前端 未结 17 2179
后悔当初
后悔当初 2020-11-22 03:45

I wrote this function to read a line from a file:

const char *readLine(FILE *file) {

    if (file == NULL) {
        printf(\"Error: file pointer is null.\"         


        
17条回答
  •  粉色の甜心
    2020-11-22 04:25

    Provide a portable and generic getdelim function, test passed via msvc, clang, gcc.

    #include 
    #include 
    #include 
    
    ssize_t
    portabl_getdelim(char ** restrict linep,
                     size_t * restrict linecapp,
                     int delimiter,
                     FILE * restrict stream) {
        if (0 == *linep) {
            *linecapp = 8;
            *linep = malloc(*linecapp);
            if (0 == *linep) {
                return EOF;
            }
        }
    
        ssize_t linelen = 0;
        int c = 0;
        char *p = *linep;
    
        while (EOF != (c = fgetc(stream))) {
            if (linelen == (ssize_t) *linecapp - 1) {
                *linecapp <<= 1;
                char *p1 = realloc(*linep, *linecapp);
                if (0 == *p1) {
                    return EOF;
                }
                p = p1 + linelen;
            }
            *p++ = c;
            linelen++;
    
            if (delimiter == c) {
                *p = 0;
                return linelen;
            }
        }
        return EOF == c ? EOF : linelen;
    }
    
    
    int
    main(int argc, char **argv) {
        const char *filename = "/a/b/c.c";
        FILE *file = fopen(filename, "r");
        if (!file) {
            perror(filename);
            return 1;
        }
    
        char *line = 0;
        size_t linecap = 0;
        ssize_t linelen;
    
        while (0 < (linelen = portabl_getdelim(&line, &linecap, '\n', file))) {
            fwrite(line, linelen, 1, stdout);
        }
        if (line) {
            free(line);
        }
        fclose(file);   
    
        return 0;
    }
    

提交回复
热议问题