簡體   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