【发布时间】:2021-06-25 23:54:58
【问题描述】:
我正在编写一个读取 ASCII 文件然后将其转换为二进制文件的程序,因为我认为这不是一项艰巨的任务,但了解背后发生的事情是......
据我所知,ASCII 文件只是人类可读的文本,所以如果我们想创建一个充满 ASCII 的新文件,一个带有 fputc() 的简单循环就足够了,而对于二进制文件 fwrite() 就足够了工作对吗?
所以我的问题是,一旦完成 ASCII 到二进制的转换,我应该在我的 .bin 文件中看到什么?应该填写完全相同的符号<88><88><88><88><88>?
代码:
/*
* From "Practical C Programming 2nd Edition"
* Exercise 14-4: Write a program that reads an ASCII file containing a list of numbers
* and writes a binary file containing the same list. Write a program that goes the
* other way so that you can check your work.
*
*/
#include <stdio.h>
#include <stdlib.h>
const char *in_filename = "bigfile.txt";
const char *out_filename = "out_file.bin";
int main()
{
int ch = 0;
/* ASCII */
FILE *in_file = NULL;
in_file = fopen(in_filename, "r");
if(!in_file)
{
fprintf(stderr, "ERROR: Could not open file %s ... ", in_filename);
exit(EXIT_FAILURE);
}
/* Binary */
FILE *out_file = NULL;
out_file = fopen(out_filename, "w+b");
if(!out_file)
{
fprintf(stderr, "ERROR: New file %s, could not be created ... ", out_filename);
exit(EXIT_FAILURE);
}
while(1)
{
ch = fgetc(in_file);
if(ch == EOF)
break;
else
fwrite(in_file, sizeof(char), 1, out_file);
}
fclose(in_file);
fclose(out_file);
return 0;
}
我正在使用这个 shell 脚本生成输入文件:
tr -dc "0-9" < /dev/urandom | fold -w100|head -n 100000 > bigfile.txt
任何帮助将不胜感激。
谢谢。
【问题讨论】:
-
也许我误解了你的作业,但是当我阅读它时,你想将你的 ASCII 测试文件读取为 数字,也许使用
fscanf(in_file, "%d", &ch)。如果你这样做,一个包含“18 52 86 120”的输入文件将产生一个包含四个字节0x12、0x34、0x56和0x78的4字节二进制输出文件。跨度> -
如果你能让它以这种方式工作,如果你给它输入
72 101 108 108 111 44 32 119 111 114 108 100 33 10,你应该最终得到一个“二进制”输出文件,毕竟它实际上也是一个文本文件。 .. -
您在这里的问题“我应该在输出中看到什么,它应该与输入相同/不同吗?”是我想问你的第一件事,也是我要问我的导师的第一件事。这不是一门英语课程,其目的是了解问题所在——它是一门编程课程。正如所写,这个问题感觉很糟糕。我希望至少有一个输入和输出样本......
-
@enhzflep 感谢您的建议,我刚改了标题,抱歉写得不好,英语不是我的第一语言。
-
@SteveSummit 感谢您的评论,我想向您请教一个很好的资源来更好地理解这些主题,因为我目前阅读的这本书我认为在某些方面非常有限......
标签: c ascii binaryfiles