c - 根据文件大小动态分配数组大小 - C

标签 c arrays dynamic-memory-allocation

有一个全局数组b[],需要在main()和其他一些函数中使用。现在这个数组的大小需要根据输入文件的大小来决定。结构类似于:

#include <stdio.h>
#include <conio.h>

char b[];

main() {

    FILE *f;

    f=fopen("Text.txt", "rb);

    if(file_size = 200)
       b[20];
    else if(file_size>200)       // I want to do something like this
       b[50];


    //Accessing b[] in the main

}

display() {

    //Accessing b[] in display

}

我应该如何通过计算文件的大小来做到这一点。由于数组 b[]main()display() 中使用,它必须是全局的。但是,我不知道如何计算文件的大小并将其分配到 main() 之前的缓冲区。

最佳答案

这里有一些代码改编自 opengl 编程 wikibook:

#include<stdlib.h>
#include <stdio.h>
#include <conio.h>

long file_size(File* file)
{
  if(input == NULL) return -1;

  long pos = ftell(input);

  if(fseek(input, 0, SEEK_END) == -1) return -1;
  long size = ftell(input);
  if(size == -1) return -1;
  if(fseek(input, pos, SEEK_SET) == -1) return -1;

  return size;
}

int display(char* b) 
{
  //Accessing b[] in display
}

int main() 
{

  FILE *f;

  f=fopen("Text.txt", "rb");

  long size = file_size(f); //returns -1 on error

  if(size == 200)
     b = malloc(20 * sizeof(char)); //replace char if you change b's type
     b = malloc(50 * sizeof(char));

  //b[0] = something, etc //access b[] 
  //display(b); //pass b to display function

  free(b);  
}

关于c - 根据文件大小动态分配数组大小 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21298988/

相关文章:

c++ - Ubuntu 中 cmake 和 OpenCV 2.0 的问题

javascript - 如何在js中转换为数组?

c - C 中的变量指针

c++ - 包含后获取#included头文件

c - 文件无法在 C 中正确保存

C和D通信

c - 在 while 循环中将值存储在数组中

arrays - 如何通过标签匹配和组匹配对该数组进行最佳排序?

c - 动态数组分配,按值传递,超出范围

C ,关于指针(或指向指针的指针?)、** 和 malloc