C read file line by line

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

    Here is my several hours... Reading whole file line by line.

    char * readline(FILE *fp, char *buffer)
    {
        int ch;
        int i = 0;
        size_t buff_len = 0;
    
        buffer = malloc(buff_len + 1);
        if (!buffer) return NULL;  // Out of memory
    
        while ((ch = fgetc(fp)) != '\n' && ch != EOF)
        {
            buff_len++;
            void *tmp = realloc(buffer, buff_len + 1);
            if (tmp == NULL)
            {
                free(buffer);
                return NULL; // Out of memory
            }
            buffer = tmp;
    
            buffer[i] = (char) ch;
            i++;
        }
        buffer[i] = '\0';
    
        // Detect end
        if (ch == EOF && (i == 0 || ferror(fp)))
        {
            free(buffer);
            return NULL;
        }
        return buffer;
    }
    
    void lineByline(FILE * file){
    char *s;
    while ((s = readline(file, 0)) != NULL)
    {
        puts(s);
        free(s);
        printf("\n");
    }
    }
    
    int main()
    {
        char *fileName = "input-1.txt";
        FILE* file = fopen(fileName, "r");
        lineByline(file);
        return 0;
    }
    

提交回复
热议问题