阅读使用C中的fscanf(每次2)HEX值序列 [英] Reading a sequence of HEX value (2 at a time) using fscanf in C

查看:321
本文介绍了阅读使用C中的fscanf(每次2)HEX值序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个文本文件,假设叫的text.txt。其格式为: 4C 4D 4E 4F (即用于字符串LMNO的十六进制值)。我已经正确打开文本文件,等等。我应该如何使用的fscanf 读四个字节(在时间,即1个字节)的顺序,在变量的每个字节存储(及其适当的数据类型)。我的最终目标是理解如何将一个字符数组中字符测试[4]存储; 字母 LMNO (即试验[0] =L,检测[1] ='M',...)


解决方案

 #包括LT&;&stdio.h中GT;诠释主要(无效){
    FILE *计划生育=的fopen(的text.txt,R);
    焦炭试验[5] = {0};
    无符号的十六进制;
    INT I;
    对于(I = 0; I&4; ++ⅰ){
        如果(1 ==的fscanf(FP,%2X,&安培;十六进制))
            测试[I] =(char)的十六进制;
        其他
            打破;
    }
    FCLOSE(FP);
    看跌(试验);
    返回0;
}

So I have a text file, assume called text.txt. Its format is: 4C 4D 4E 4F (i.e the hex values for the character string "LMNO"). I have correctly opened the text file, etc. How should I use fscanf to read the sequence of four bytes (i.e 1 byte at a time), storing each byte in a variable (with its appropriate data type). My end goal is to understand how to store in a character array char test[4]; the letters LMNO (i.e test[0] = 'L', test[1] = 'M',...)

解决方案

#include<stdio.h>

int main(void){
    FILE *fp = fopen("text.txt", "r");
    char test[5] = {0};
    unsigned hex;
    int i;
    for(i=0; i < 4; ++i){
        if(1==fscanf(fp, "%2x", &hex))
            test[i] = (char)hex;
        else
            break;
    }
    fclose(fp);
    puts(test);
    return 0;
}

这篇关于阅读使用C中的fscanf(每次2)HEX值序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆