C语言实现从指定位置(偏移地址)截取文件内容

源代码:

#include 
#include 
#include 
#include 
#include 
#include 

#define FILE_OFFSET 10  
#define EXE_ABORT() {system("pause");return 0;}

#define FILE_NAME_I "./test.txt"
#define FILE_NAME_O "./test_out.txt" 

int main(int argc, char *argv[])
{
    uint32_t offset = FILE_OFFSET;
    char filename_i[300];
    char filename_o[300];
    FILE *fp_i;
    FILE *fp_o;
    char ch = 0;
    int ret = 0;

    struct stat stat_i;
    struct tm *tm_p;
    
    strcpy(filename_i, FILE_NAME_I);
    strcpy(filename_o, FILE_NAME_O);
    
    printf("filname_i = %s\n", filename_i);
    printf("filname_o = %s\n", filename_o);

    ret = stat(filename_i, &stat_i);
    if(ret != 0)
    {
        printf("%s: get file stat failed", filename_i);
        EXE_ABORT();
    }
    printf("get file stat success\n");
    //! 文件的大小,字节为单位
    printf("size of the file in bytes: %.02f MB (%d Bytes)\n", stat_i.st_size / 1024.0, stat_i.st_size);//    
    
    fp_i = fopen(filename_i, "rb");
    fp_o = fopen(filename_o, "wb");

    if(fp_i == NULL)
    {
        printf("%s open failed\n", filename_i);
        EXE_ABORT();
    }

    if(fp_o == NULL)
    {
        printf("%s open failed\n", filename_o);
        EXE_ABORT();
    }

    printf("offset = %d(0x%x)\n", offset, offset);
    fseek(fp_i, offset, SEEK_SET);

    while(1)
    {
        ch = fgetc(fp_i);
        if(feof(fp_i))
            break ;
        fputc(ch, fp_o);
    }

    fclose(fp_i);
    fclose(fp_o);

    printf("截取完成\n");

    system("pause");
    return 0;
}

运行结果:


输入文件test.txt内容:

1234567890ABCDEFGHIJKLMOPQRSTUVWXYS

偏移量设定为10,截取后的test_out.txt文件内容:

ABCDEFGHIJKLMOPQRSTUVWXYS

更方便的,可以argc参数,来实现通过指定输入文件路径和指定偏移量。

你可能感兴趣的:(c语言,开发语言,Verilog,FPGA,Xilinx)