从文件中读取ASCII字符到数组中

时间:2016-03-21 01:57:35

标签: c arrays

嘿伙计们,我一直坚持如何从文件中读取和扫描ASCII字符到数组中。该文件将包含长度不超过512字节的ASCII数据。

我知道我需要动态分配内存,但不知道我应该多大才能读取文件以及如何让它知道它已达到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循环但是我怎么知道它运行到什么条件?

感谢您的帮助!

1 个答案:

答案 0 :(得分:-1)

我希望这有帮助。基本上,我从你的问题中理解的是,你希望能够读取文件,将其存储在数组中,并能够像打印值一样操纵这个数组。

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