C语言读文件怎么样检测从一个位置读起,然后转存到另一个数组中,再创建一个文件写出

C语言 码拜 8年前 (2016-04-21) 1034次浏览
C语言读文件怎么样检测从一个位置读起,然后转存到另一个数组中,再创建一个文件写出
例如一个2000字节的文件,开头有一串长度不定乱码,乱码后有一句start,要求从start结束后开始读取后面的全部数据,数据长度当然要减去之前乱码的长度和start的长度。然后再将读取的数据写入到1.txt(本人创建的文件)中
解决方案

5

使用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;
}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C语言读文件怎么样检测从一个位置读起,然后转存到另一个数组中,再创建一个文件写出
喜欢 (0)
[1034331897@qq.com]
分享 (0)