c - 格式化 C 程序

标签 c char format hex

所以我有一个程序,它获取一个文件并逐字符读取并打印该字符和十六进制等效值。 `

#include <stdio.h>
#include <stdlib.h>

int main(){
FILE *labFile;
char buf;

labFile = fopen("lab1.dat", "r");
if (labFile == NULL) perror("Error opening file\n");

   while( (buf = fgetc(labFile) ) != EOF){
        if(("%x", buf)< 16){
            printf("%c 0%x\n", buf, buf);
        }
        else
            printf("%c %x\n", buf, buf);
   }
   fclose(labFile);
   return 0;
}

` 该程序按照我需要的方式运行,除了一件事之外。我需要程序在顶部输出十六进制数字,然后在数字正下方输出字符,并且此过程需要水平继续。

任何帮助将不胜感激!

最佳答案

您应该首先将字符输出为十六进制,然后保存已打印的每个读入字符,直到用完屏幕上的列为止。然后,您可以移至下一行,并打印出十六进制输出下保存的字符。

您可以简化逻辑,将十六进制输出格式化为单个打印语句。

当打印出字符时,你需要有一个计划来表示不可打印的字符。在下面的示例程序中,我们通过打印两个连续的点来处理它。

void print_chars (unsigned char *p, int num) {
   int i;
   for (i = 0; i < num; ++i) {
      printf("%s%c%s",
             isprint(p[i]) ? " "  : ".",
             isprint(p[i]) ? p[i] : '.',
             (i < num-1) ? " " : "\n");
   }
}

int main() {
   FILE *labFile;
   char buf;
   int count = 0;
   int num = COLUMNS/3;
   char printed[num];
   labFile = fopen("lab1.dat", "r");
   if (labFile == NULL) perror("Error opening file\n");
   while( (buf = fgetc(labFile) ) != EOF) {
      printf("%s%02x", count ? " " : "", buf);
      printed[count++] = buf;
      if (count == num) {
         count = 0;
         putchar('\n');
         print_chars(printed, num);
      }
   }
   fclose(labFile);
   if (count) {
      putchar('\n');
      print_chars(printed, count);
   }
   return 0;
}

列数除以 3,因为每个字符大约需要 3 列用于输出(2 个十六进制字符和一个空格)。检索列数取决于系统,但如果您愿意,可以插入 80。

关于c - 格式化 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18603408/

相关文章:

c - 返回具有多个可能值的 char 指针

objective-c - 枚举按位掩码限制

字符指针和空间搜索

c - 无法从内核模式读取 PCI BAR

c - 为什么当我超出另一个数组的边界时 printf() 的输出会发生变化?

java - Birt 报告中的数字格式为小数

xml - 选择什么设置存储格式?

python语言环境货币到0小数

我可以命名一个与 typedef 结构名称同名的变量吗?

c - 如何设置 openMP