C/C++二进制读取文件总结

[TOC]

fread 与fwrite

只看fread与fwrite用法即可

参考:

  1. C语言 fread()与fwrite()函数说明与示例

测试fread和fwrite读取vector数组,采用循环遍历的方式

#include 
#include 
#include 
#include 
using namespace std;
//fwrite写vector
int main()
{
    FILE *fp;
    fp = fopen("vector.outfile", "wb");
    if (!fp)
    {
        printf("打开%s文件失败\n", "vector.outfile");
        return false;
    }
    vector s;
    int idx = 0;
    for (idx = 0; idx < 1000; idx++)
    {
        s.push_back(idx);
    }
    for (idx = 0; idx < 1000; idx++)
    {
        fwrite(&s[idx], 1, sizeof(s[idx]), fp);
    }
    fclose(fp);
    for (idx = 0; idx < 1000; idx++)
    {
        s[idx] = 0;
    }
    fp = fopen("vector.outfile", "rb");
    if (!fp)
    {
        printf("以二进制读取方式打开%s文件失败\n", "vector.outfile");
        return false;
    }
    for (idx = 0; idx < 1000; idx++)
    {
        fread(&s[idx], 1, sizeof(s[idx]), fp);
    }
    for (idx = 0; idx < 1000; idx++)
    {
        std::cout << "s["<

合并jpg、txt文件到一个文件

#include 
#include 
#include
using namespace std;
int main()
{
    FILE * fpPhoto, *fpText, *fpTarget; //定义文件指针
    int iRead;
    char szBuf[100];

    printf("请输入第一个文件名(jpg):\n");
    gets(szBuf);
    fpPhoto = fopen(szBuf, "rb"); //打开文件
    printf("请输入第二个文件名(txt):\n");
    gets(szBuf);
    fpText = fopen(szBuf, "rb");
    printf("请输入目的文件名(jpg):\n");
    gets(szBuf);
    fpTarget = fopen(szBuf, "wb");

    if (!fpPhoto || !fpText || !fpTarget)
    {
        printf("打开文件失败!\n");
        system("pause");
        return -1;
    }
    //读入字节流
    while ((iRead = fread(szBuf, 1, sizeof(szBuf), fpPhoto)) > 0)
        fwrite(szBuf, 1, iRead, fpTarget);
    //读入字节流,写入文件
    while ((iRead = fread(szBuf, 1, sizeof(szBuf), fpText)) > 0)
        fwrite(szBuf, 1, iRead, fpTarget);

    fclose(fpPhoto);
    fclose(fpText);
    fclose(fpTarget);
    return 0;
}

第一个文件1.jpg
第二个文件1.txt
目的文件名target.jpg
合并之后target.jpg的字节数 = 1.jpg + 1.txt

  • 1.jpg
C/C++二进制读取文件总结_第1张图片
1.jpg
  • 1.txt
helloworld
  • target.jpg
C/C++二进制读取文件总结_第2张图片
target.jpg

获取文件的大小字节数

#include
#include 
#include
using namespace std;
int main(int argc, char *argv[])
{
    char *file_name = argv[1];
    struct stat st;
    // get the file size.
    if (stat(file_name, &st) < 0)
    {
        perror("stat: ");
        return -1;
    }
    off_t file_size;
    file_size = st.st_size;
    cout << "file_size:" << file_size << endl;
    return 0;
}

你可能感兴趣的:(C/C++二进制读取文件总结)