简体   繁体   English

将ASCII字符从文件读入数组

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

Hey guys so I'm stuck on how to read and scan in ASCII characters into an array from a file. 大家好,我将继续介绍如何从文件读取ASCII字符并将其扫描到数组中。 The file will consist of ASCII data of varying length up to 512 bytes. 该文件将包含可变长度的ASCII数据,最大为512字节。

I know I need to dynamically allocate memory but not sure how large I should make it in order to read in the file and how to let it know that it reached EOF 我知道我需要动态分配内存,但不确定要读取文件时应增加多少内存,以及如何让它知道已达到EOF

An example of an input file is: 输入文件的示例是:

abcdefghijklmnopqrstuvwxyz12345

I was thinking something along the lines of: 我在考虑以下方面:

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);

and then if I wanted to print back the array how would I move through the array without knowing the length? 然后,如果我想打印回数组,我将如何在不知道长度的情况下遍历数组? I can only think of using a for loop but how would I know what condition to make it run until? 我只能想到使用for循环,但是我怎么知道使其运行到什么条件呢?

Thank you for your help! 谢谢您的帮助!

I hope this help. 希望对您有所帮助。 Basically, what I understand from your question is that you want to be able to read the file, store it in the array and be able to manipulate this array like printing values back. 基本上,我从您的问题中了解到的是,您希望能够读取文件,将其存储在数组中并能够像回打印值一样操作该数组。

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