作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我应该制作一个读取和写入二进制文件的 C 程序。它需要 2 个参数:
输入文件的名称 (.wav)
输出文件的名称 (.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/
我是一名优秀的程序员,十分优秀!