C read file line by line

前端 未结 17 2351
后悔当初
后悔当初 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:05

    If your task is not to invent the line-by-line reading function, but just to read the file line-by-line, you may use a typical code snippet involving the getline() function (see the manual page here):

    #define _GNU_SOURCE
    #include 
    #include 
    
    int main(void)
    {
        FILE * fp;
        char * line = NULL;
        size_t len = 0;
        ssize_t read;
    
        fp = fopen("/etc/motd", "r");
        if (fp == NULL)
            exit(EXIT_FAILURE);
    
        while ((read = getline(&line, &len, fp)) != -1) {
            printf("Retrieved line of length %zu:\n", read);
            printf("%s", line);
        }
    
        fclose(fp);
        if (line)
            free(line);
        exit(EXIT_SUCCESS);
    }
    

提交回复
热议问题