例如一个2000字节的文件,开头有一串长度不定乱码,乱码后有一句start,要求从start结束后开始读取后面的全部数据,数据长度当然要减去之前乱码的长度和start的长度。然后再将读取的数据写入到1.txt(本人创建的文件)中
解决方案
5
使用ftell移动到需要读取的位置
参考:http://en.cppreference.com/w/c/io/ftell
参考:http://en.cppreference.com/w/c/io/ftell
5
char buf[2000];
FILE *f;
int i;
f=fopen(...,"rb");
fread(buf,1,2000,f);
fclose(f);
for (i=0;i<2000-5;i++) if (0==memcmp(buf+i,"start",5)) break;
f=fopen("1.txt","wb");
fwrite(buf+i+5,1,2000-i-5,f);
fclose(f);
10
#include <stdio.h>
#include <io.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
char *buf;
long flen;
FILE *f;
int i;
int main() {
f=fopen("in.dat","rb");
if (NULL==f) {
printf("Can not open file in.dat!\n");
return 1;
}
flen=_filelength(_fileno(f));
buf=(char *)malloc(flen);
if (NULL==buf) {
fclose(f);
printf("Can not malloc %d bytes!\n",flen);
return 1;
}
fread(buf,1,flen,f);
fclose(f);
for (i=0;i<flen-5;i++) if (0==memcmp(buf+i,"start",5)) break;
f=fopen("1.txt","wb");
fwrite(buf+i+5,1,flen-i-5,f);
fclose(f);
free(buf);
return 0;
}