簡體   English   中英

將ASCII字符從文件讀入數組

[英]Reading in ASCII characters from a file into an array

大家好,我將繼續介紹如何從文件讀取ASCII字符並將其掃描到數組中。 該文件將包含可變長度的ASCII數據,最大為512字節。

我知道我需要動態分配內存,但不確定要讀取文件時應增加多少內存,以及如何讓它知道已達到EOF

輸入文件的示例是:

abcdefghijklmnopqrstuvwxyz12345

我在考慮以下方面:

char* array = malloc(512 * sizeof(char); //but that doesnt seem right,
do{
    c = fgetc(enc) // enc is FILE Ptr
    array[i++] = c
    if(feof(enc))
       break;
while(1);

然后,如果我想打印回數組,我將如何在不知道長度的情況下遍歷數組? 我只能想到使用for循環,但是我怎么知道使其運行到什么條件呢?

謝謝您的幫助!

希望對您有所幫助。 基本上,我從您的問題中了解到的是,您希望能夠讀取文件,將其存儲在數組中並能夠像回打印值一樣操作該數組。

int main(int argc, char** argv) {

       FILE* enc = fopen("data","r");
       int number=0; 
       char data[80];int i=0;

       if (! enc ) // equivalent to saying if ( in_file == NULL ) 
         {  
            printf("oops, file can't be read\n"); 
            exit(-1); 
         }

      while ( fscanf(enc, "%c", & number ) == 1 )  
         { 

             data[i] = number;
               i++;
             //printf("We just read %c\n", data[i]); 

         } 

    int j=0;

    while(data[j]!=NULL)
    {
      printf("%c", data[j]);
      j++;
     }
   return (0);
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM