C read file line by line

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

    //open and get the file handle
    FILE* fh;
    fopen_s(&fh, filename, "r");
    
    //check if file exists
    if (fh == NULL){
        printf("file does not exists %s", filename);
        return 0;
    }
    
    
    //read line by line
    const size_t line_size = 300;
    char* line = malloc(line_size);
    while (fgets(line, line_size, fh) != NULL)  {
        printf(line);
    }
    free(line);    // dont forget to free heap memory
    

提交回复
热议问题