[英]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.