1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
int main(void){
FILE *f=fopen("/home/wzpc/c/1.mp3","rb");
if(f==NULL){
puts("file error\n");
}
char c[1000];
char *p=malloc(sizeof(char));
int t=0;
while(!feof(f)){
memset(c,0,1000);
fread(c,1000,1,f); //与fgetc() 相同,读文件指针自动累加
p=realloc(p,1000*(t+1)); //增加动态内存
memcpy(&p[t*1000],c,1000); //拷贝,一定要注意指定开始拷贝的地址
t++;
}
printf("%s\n",p);
free(p);
return 0;
}
2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(void){
FILE *f=fopen("/home/wzpc/c/1.mp4","rb");
if(f==NULL){
puts("file error\n");
}
long int n=0;
while(!feof(f)){
fgetc(f);
n++;
}
rewind(f);
char *c=calloc(n,sizeof(char));
fread(c,n,1,f);
printf("%s\n","over");
free(c);
return 0;
}
第二种方法是读文件到数组的最快方法,第一种慢。