二进制文件I / O. (感觉这个操作有一个心理障碍)

时间:2015-01-26 05:43:32

标签: c io binaryfiles

我应该制作一个读写二进制文件的C程序。它需要2个参数:

  1. 输入文件的名称(.wav)

  2. 输出文件的名称(.wav)

  3. 我需要读取输入.wav文件的前44个字节并将其写入输出.wav文件。然而,这对我来说是全新的,我已经观看了几个视频,但仍然没有完全掌握缓冲区,短路,size_T变量类型的概念。

    这是我的问题,我明白你需要初始化两个指针(输入,输出文件)

    #include <stdio.h>
    #include <stdlib.h>
    #include <errno.h>
    int main(int argc, char **argv){
    
     if (argc != 2){
        fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
        exit(1);
        }
    
      FILE *ipfile, *opfile;
      char *buffer;    //what does this even do? Apparently this is a block of memory that I will store what I read/write?
    
      ipfile = fopen(argv[1], "rb+");
      opfile = fopen(argv[2], "wb+");
    
      short first_44[44];   //i think this is where i'm storing the first 44 bytes?
    
      fread(&first_44, sizeof(short), 44, ipfile); //So i think that i'm reading from ipfile and reading up until 44 bytes and storing it in first_44 ?
    
      fwrite(&first_44, sizeof(short), 44, opfile); //I think this is just writing what was in first_44 to opfile
    
      fclose(ipfile);
      fclose(opfile);
    
      return 0;
      }
    

    任何人都会看到这段代码有什么问题,也许可以帮助我更好地理解i / o(从二进制文件中读取并将您读到的内容写入另一个文件)

    谢谢!

1 个答案:

答案 0 :(得分:1)

更正类似的代码。

int main(int argc, char **argv)
{
    FILE *ipfile, *opfile;
    char *buffer;
    const int bytes = 44;

    if (argc != 3)
    {
        fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
        return 0;
    }

//  open file
    ipfile = fopen(argv[1], "rb");
    opfile = fopen(argv[2], "wb");

//  check if files opened   
    if (!ipfile)
    {
        printf ("Error opening input file\n");
        return 0;
    }
    if (!opfile)
    {
        printf ("Error opening output file\n");
        fclose (ipfile);
        return 0;
    }

//  allocate memory
    buffer = malloc (bytes);

//  read input file
    if (fread (buffer, bytes, 1, ipfile)!=1 )
    {
        printf ("Error reading input file\n");
        fclose (ipfile);
        fclose (opfile);
        free (buffer);
        return 0;
    }

//  write out
    if (fwrite(buffer, bytes, 1, opfile)!=1 )
    {
        printf ("Error writing output file\n");
        fclose (ipfile);
        fclose (opfile);
        free (buffer);
        return 0;
    }

//  close files
    fclose(ipfile);
    fclose(opfile);
    free (buffer);

//  success 
    printf ("Done!\n");
    return 1;
}