首页 > 解决方案 > 如何使用 C 读取视频文件

问题描述

我有一个视频文件,想阅读它并在 anathor 文件中显示结果。

FILE *fp1,*fp2;

fp1=fopen("FOOTBALL_352x288_30_orig_01.yuv","rb");   
fp2=fopen("FOOTBALL_352x288_30_copy_01.yuv","wb");

while (feof(fp1))
{
  fread(1,sizeof(int),fp1);
  fwrite(fp1,sizeof(int),fp2);
}

fclose(fp1);
fclose(fp2);

标签: cvideoyuv

解决方案


你或多或少想要这样的东西:

#include <stdlib.h>
#include <stdio.h>

#define BUFFERSIZE 0x8000 // 32k buffer (adapt at will)

int main()
{
  FILE *fp1 = fopen("FOOTBALL_352x288_30_orig_01.yuv", "rb");

  if (fp1 == NULL)
  {
    // display error message to be written
    exit(1);
  }
  FILE *fp2 = fopen("FOOTBALL_352x288_30_copy_01.yuv", "wb");
  if (fp2 == NULL)
  {
    // display error message to be written
    exit(1);
  }    

  for (;;)   // loop for ever
  {
    char buffer[BUFFERSIZE];
    size_t bytesread = fread(buffer, 1, sizeof buffer, fp1);

    // bytesread contains the number of bytes actually read
    if (bytesread == 0)
    {
      // no bytes read => end of file
      break;
    }

    fwrite(buffer, bytesread, 1, fp2);
  }

  fclose(fp1);
  fclose(fp2);
}

免责声明:这是未经测试的代码,但您应该明白这一点。

仍有进一步改进的空间,尤其是文件结尾以外的实际读取错误(很少发生)没有得到正确处理。


推荐阅读