Read file contents with unknown size

后端 未结 3 344
小鲜肉
小鲜肉 2021-01-14 11:44

I want to process the contents of a config file. The config file could be any size. I am getting a Bus Error, after the program hangs, when I run the following code:

3条回答
  •  旧巷少年郎
    2021-01-14 12:11

    In C99, and assuming your config file should not be in the MiB or larger range, you could use a VLA:

    FILE *fp = fopen(CONFIG_FILE, "r");
    if (fp == NULL) {
        // error handling and cleanup omitted for brevity
    }
    
    struct stat st;
    fstat(fileno(fp), &st);  // Error check omitted
    char buffer[st.st_size+1];
    fread(buffer, sizeof(char), st.st_size, fp);
    buffer[st.st_size] = '\0';
    fprintf(stderr, "%s\n", *buffer);
    fclose(fp);
    

提交回复
热议问题