简体   繁体   中英

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. The file will consist of ASCII data of varying length up to 512 bytes.

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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