繁体   English   中英

如何读取大输入-C语言中的8MB数据

[英]how to Read large input - 8MBdata in C

我有一个问题,我必须从输入文件中读取大数据(8mb)。我试图给出array的大小。 有什么有效的方法可以重写代码

#include <stdio.h>
#include <stdlib.h>
int main()
 {

FILE *f;
char msg[9000000]=" ";  
int i=0;
f=fopen("file.txt","r");
while((msg[i]=fgetc(f))!=EOF){
        i++;
        }
 printf("\nThe data from the file is :%s\n",msg);
fclose(f);
return 0;
 }

在这种情况下,您可以只写读取的内容,而不必将所有内容保存在内存中。

#include <stdio.h>
#include <stdlib.h>
int main(void)
{

    FILE *f;
    int msg;
    int inputExists = 0;
    f=fopen("file.txt","r");
    if(f == NULL){
        perror("fopen");
        return 1;
    }
    printf("\nThe data from the file is :");
    while((msg=fgetc(f))!=EOF){
        putchar(msg);
        inputExists = 1;
    }
    if(!inputExists) putchar(' ');
    printf("\n");
    fclose(f);
    return 0;
}

非静态局部变量(通常,尽管C标准不需要)存储在堆栈中。 在大多数系统中,该堆栈的大小相当有限,通常约为1 MB甚至更少。

因此,您应该将数据存储在堆上或静态内存中的其他位置。 首选使用堆:

#include <stdio.h>
#include <stdlib.h>
#define MAX (8 * 1024 * 1024)
int main () {
  char * data = malloc(MAX);
  // add error checks
  int in;
  size_t position = 0;
  while ((in = fgetc(stdin)) != EOF && position < MAX) {
    data[position++] = in & 0xFF;
  }
  // Note: data is NOT a string, no null termination
  // also check for errors
  free(data);
  return 0;
}

需要注意的两件事:我还在检查缓冲区是否不会溢出。 这非常重要,您应该确保要读取和写入的每个缓冲区。

其次,正如任何参考资料都会告诉您的那样, fgetc的返回值为int 这很重要,因为EOF可以是无法用char表示的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM