简体   繁体   English

ansi c fread 16 位整数并将其作为 ascii 文本文件 fwrite

[英]ansi c fread 16-bit integer and fwrite it as an ascii textfile

I have a binary file that contains 16-bit integer data and i want to convert it to ASCII readable data.我有一个包含 16 位整数数据的二进制文件,我想将其转换为 ASCII 可读数据。

My question is how do I use fread(&buffer,sizeof(buffer) or 16,1,fp);我的问题是如何使用fread(&buffer,sizeof(buffer)16,1,fp); to read the file and use again fwrite(buffer, sizeof(buffer)/7, 1, file);读取文件并再次使用fwrite(buffer, sizeof(buffer)/7, 1, file); to write the data to a file.将数据写入文件。

16 in fread is 16-bit and wants to know where it goes or in what form it goes and if in fwrite I will put 7 for 7-bit. fread中的 16 是 16 位,想知道它去哪里或以什么形式去,如果在 fwrite 中,我会将7放入7位。

Please provide a code snippet example in C. I want to have the resultant file to be an ordinary readable text file.请提供 C 中的代码片段示例。我希望生成的文件是一个普通的可读文本文件。

You have many things that are confusing.你有很多令人困惑的事情。

Assuming buffer is a magically sized properly to fit the file uint8_t array, you can read it in (from a file fopen() ed in binary mode ) using:假设buffer是一个神奇的大小以适合文件uint8_t数组,您可以使用以下方法读取它(从文件fopen() ed in binary mode ):

fread(buffer, sizeof buffer, in);

That'd give you all of the bits in buffer , if it doesn't fail.如果它没有失败,那将为您提供buffer所有位。

Then, the output is simply:然后,输出很简单:

FILE * const out = fopen("numbers.txt", "wt");
if(out != NULL)
{
  for(size_t i = 0; i < sizeof buffer; i += 2)
  {
    const unsigned int here = buffer[i] + 256 * buffer[i + 1];
    fprintf(out, "%u\n", here);
  }
  fclose(out);
}

This assumes little-endian byte ordering in the binary file.这假定二进制文件中的小端字节序。 Swap the indexes in the here assignment for big-endian.here分配中的索引交换为 big-endian。 It also assumes unsigned 16-bit numbers.它还假定为无符号 16 位数字。

after adjusing my code as below the result i get unsigned int,since am expecting data result with alphabetical characters.what additional code can i add to turn it alphabetical?在将我的代码调整为下面的结果后,我得到了 unsigned int,因为我期望数据结果带有字母字符。我可以添加什么额外的代码来将它变成字母?

 #include<stdio.h>
    int main()
       {
    FILE *fp,*out;
  char buffer[256];
          size_t i = 0;
            fp=fopen("c:/Gosam/input.txt", "rb");
            if(out != NULL)
           {
            fread(buffer, sizeof buffer,1, fp);
              }
        out = fopen("c:/Gosam/res.txt", "w");
if(out != NULL)
{
   // buffer = (char*) malloc (sizeof(char)*Size);

  for( i = 0; i < sizeof(buffer); i += 2)
  {
    const unsigned int var = buffer[i] + 256 * buffer[i + 1];
    fprintf(out, "%u\n", var);
  }
  fclose(out);
}
fclose(fp);

}

these are my results but i want to turn them to alphabetical strings.这些是我的结果,但我想将它们转换为字母字符串。

263
4294966987
4294967222
4294967032
64
4294967013
73
4294967004
90
4294967028
83
4294966975
37
4294966961
5
4294966976
82
4294966942
4294967022
4294966994
11
4294967024
29
4294966985
4294966986
4294966954

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM