gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:24:57 24 4
gpt4 key购买 nike

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

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

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

我需要读取输入 .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(从二进制文件读取并将读取的内容写入另一个文件)

谢谢!

最佳答案

更正代码。

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

关于c - 二进制文件 I/O。 (感觉这个操作有心理障碍),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28145265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com