fscanf多行[c ++] [英] fscanf multiple lines [c++]
问题描述
我正在阅读包含多行数据的文件,例如:
:100093000202C4C0E0E57FB40005D0E0020C03B463
:1000A3000105D0E0022803B40205D0E0027C03027C
:1000B30002E3C0E0E57FB40005D0E0020C0BB4011D
我正在逐字节读取值并将它们存储在数组中。
fscanf_s(in_file,%c,& sc); // start code
fscanf_s(in_file,%2X,& iByte_Count); // byte count
fscanf_s(in_file,%4X,& iAddr); // 2 byte address
fscanf_s(in_file,%2X,& iRec_Type); // record type
for(int i = 0; i< iByte_Count; i ++)
{
fscanf_s(in_file,%2X,& iData [i] ;
iArray [(iMaskedAddr / 16)] [iMaskedNumMove + 3 + i] = iData [i];
}
fscanf_s(in_file,%2X,& iCkS);
这很好,除非我到第一行结束。我需要这个重复,直到我到文件的末尾,但当我把它放在一个循环中它发生了。
我可以强制位置到下一行的开始吗?
我知道我可以使用流和所有的,但我正在处理这种方法。
感谢您的帮助
fscanf_s
并使用 fgets
或 std :: getline
。 也就是说,你的问题是处理换行符,下一个记录开头是':'。
一种方法是使用 fscanf_s(%c)
,直到读取':'字符文件结束:
char start_of_record;
do
{
fscanf_s(infile,%c,& start_of_record);
} while(!feof(infile)&&(start_of_record!=':'));
//现在处理标题....
OP正在读取的数据是用于传输二进制数据的标准格式,通常用于下载到闪存和EPROM中。
I am reading in a file with multiple lines of data like this:
:100093000202C4C0E0E57FB40005D0E0020C03B463
:1000A3000105D0E0022803B40205D0E0027C03027C
:1000B30002E3C0E0E57FB40005D0E0020C0BB4011D
I am reading in values byte by byte and storing them in an array.
fscanf_s(in_file,"%c", &sc); // start code
fscanf_s(in_file,"%2X", &iByte_Count); // byte count
fscanf_s(in_file,"%4X", &iAddr); // 2 byte address
fscanf_s(in_file,"%2X", &iRec_Type); // record type
for(int i=0; i<iByte_Count; i++)
{
fscanf_s(in_file,"%2X", &iData[i]);
iArray[(iMaskedAddr/16)][iMaskedNumMove+3+i]=iData[i];
}
fscanf_s(in_file,"%2X", &iCkS);
This is working great except when I get to the end of the first line. I need this to repeat until I get to the end of the file but when I put this in a loop it craps out.
Can I force the position to the begining of the next line?
I know I can use a stream and all that but I am dealing with this method.
Thanks for the help
My suggestion is to dump fscanf_s
and use either fgets
or std::getline
.
That said, your issue is handling the newlines, and the next beginning of record token, the ':'.
One method is to use fscanf_s("%c")
until the ':' character is read or the end of file is reached:
char start_of_record;
do
{
fscanf_s(infile, "%c", &start_of_record);
} while (!feof(infile) && (start_of_record != ':'));
// Now process the header....
The data the OP is reading is a standard format for transmitting binary data, usually for downloading into Flash Memories and EPROMs.
这篇关于fscanf多行[c ++]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!