C read file line by line

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

    Implement method to read, and get content from a file (input1.txt)

    #include 
    #include 
    
    void testGetFile() {
        // open file
        FILE *fp = fopen("input1.txt", "r");
        size_t len = 255;
        // need malloc memory for line, if not, segmentation fault error will occurred.
        char *line = malloc(sizeof(char) * len);
        // check if file exist (and you can open it) or not
        if (fp == NULL) {
            printf("can open file input1.txt!");
            return;
        }
        while(fgets(line, len, fp) != NULL) {
            printf("%s\n", line);
        }
        free(line);
    }
    

    Hope this help. Happy coding!

提交回复
热议问题