一个关于用C语言读取文件内容的问题。
想用fread函数来读取一个文件的内容,只知道文件中有数字和字符,但不知道具体有多少。
该怎么写呢??? 还有就是C语言中怎么读入未知数目的字符,用什么来存放(不是那种用一个很大的字符数组)?
高手指点一下!!小弟谢谢了。
[解决办法]
C语言读取文件数据一般都用字符数组存储,这样读取到数组后的后期处理也会方便点,担心空间不够的话就用动态数组。
#include <stdio.h>
#include <stdlib.h>
int main () {
FILE * pFile;
long lSize;
char * buffer;
size_t result;
pFile = fopen ( "myfile.txt" , "rb" );
if (pFile==NULL)
{fputs ("File error",stderr); exit (1);} // obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);
if (buffer == NULL)
{fputs ("Memory error",stderr); exit (2);}
// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
if (result != lSize)
{fputs ("Reading error",stderr); exit (3);}
/* 这时候全部的文件数据都保存到了 buffer 里,你可以根据需要进行处理 */
// terminate
fclose (pFile);
free (buffer);
return 0;
}