菜鸟一个,求助高手。。
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <malloc.h>
#include <stdlib.h>
//获取文件的大小
unsigned long get_file_size(char *filename)
{
struct stat buf;
if(stat(filename,&buf)<0)
return 0;
return (unsigned long)buf.st_size;
}
int main(int argc,char *argv[])
{
FILE *fd;
FILE *fw;
int *buffer=(int *)malloc((get_file_size(argv[1]))*sizeof(int));
fopen_s(&fd,argv[1],"r");
fopen_s(&fw,argv[2],"w+");
fread(buffer,1,get_file_size(argv[1]),fd);
buffer[get_file_size(argv[1]+1)]='\0';
fwrite(buffer,1,get_file_size(argv[1]),fw);
fclose(fd);
fclose(fw);
return 0;
}
为什么,我写入的文件比读取得大了。
[解决办法]
如果你是读写二进制文件,打开文件时需要指定参数b,我帮你改一下代码:
#include <stdio.h>#include <string.h>#include <fcntl.h>#include <sys/stat.h>#include <malloc.h>#include <stdlib.h>// 获取文件的大小unsigned long get_file_size(char *filename){ struct stat buf; if (stat(filename, &buf) < 0) return 0; return (unsigned long)buf.st_size;}int main(int argc,char *argv[]){ if (argc < 3) return -1; unsigned long dwFileSize = get_file_size(argv[1]); unsigned char *buffer = (unsigned char *)malloc(dwFileSize); FILE *fr; FILE *fw; fopen_s(&fr, argv[1], "rb"); fopen_s(&fw, argv[2], "wb"); fread(buffer, 1, dwFileSize, fr); fwrite(buffer, 1, dwFileSize, fw); fclose(fr); fclose(fw); free(buffer); return 0;}
[解决办法]
媒体文件不能简单合并,还要修改文件头。