Linux下读取文件内容存放到数组中(C语言实现)
具体使用函数FILE *fopen(const char *path,const char *mode);
其实用方式为:文件指针名=fopen(文件名,使用文件方式);
例如:
FILE *fp;
fp=fopen("file a","r");
其意义是在当前目录下打开文件file a,只允许进行“读”操作,并使fp指向该文件。
下面代码为具体实现方法:
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<sys/stat.h>
#include<stdlib.h>
int main(int argc,char* argv[])
{
FILE *fp = NULL;
fp = fopen("001.PCM","rb"); //打开文件
if(fp == NULL)
{
printf("--: %s---%d--001.PCM open error",__FILE__,__LINE__);
}
fseek(fp,0L,SEEK_END); //定位到文件末尾
int flen = ftell(fp); //得到文件大小
char *p = (char *)malloc(flen+1); //分配空间存储文件中的数据
if(p == NULL)
{
fclose(fp);
return 0;
}
fseek(fp,0L,SEEK_SET); //定位到文件开头
fread(p,flen,1,fp); //一次性读取全部文件内容
p[flen] = '\0'; // 字符串最后一位为空
printf("file flen is %d\n\n",flen);
printf("read file buff is %s",p);
}
GCC下编译通过