使用fscanf时的宽度作为变量

我试图读取文件的某个部分,并且每行的数据量不同但我知道我想要多少字节的信息。 像这样:

5bytes.byte1byte2byte3byte4byte5CKSum //where # of bytes varies for each line (and there is no period only there for readability) 

实际数据:

 05AABBCCDDEE11 03AABBCC22 04AABBCCDD33 

所以我希望我的宽度是这样的变量:

 fscanf_s(in_file,"%variableX", &iData); 

这是可能的,因为现在我想我必须创建一个案例陈述?

不幸的是,不,printf中没有像’*’这样的修饰符会导致scanf从变量中获取其字段宽度或精度。 您最接近的是动态创建格式字符串:

 char format[8]; sprintf(format, "%%%dX", width); fscanf(in_file, format, &iData); 

如果您真的希望能够以编程方式调整fscanf格式,可以尝试使用足够的空间堆栈分配字符串,然后生成如下格式:eg eg

 char formatString[100]; // writes "%max_size[0-9]", substituting max_size with the proper digits sprintf(formatString, "%%%d[0-9]", MAX_SIZE); fscanf(fp, formatString, buffer); // etc... 

带有%X的fscanf将自动停在换行符,对吧? 如果这些字段确实是换行符(如你的例子中所示),那么你不能只是调用

 fscanf(in_file, "%X", &iData); 

让fscanf找出结局的位置?

您也可以考虑使用C ++流。

 #include  #include  // open the file and create a file input stream ifstream file("test.txt" , ios::in | ios::binary); // loop through the whole file while (ifs.good()) { // extract one byte as the field width unsigned char width; file.read(&width, 1); // extract width number of unformatted bytes char * bytes = new char[width]; file.read(bytes, width); // process the bytes ... delete [] bytes; // skip EOL characters if needed // file.seekg(1, ios_base::cur) } file.close(); 

如果您似乎指出包含换行符,则更简单的方法是使用getLine()。 查看http://www.cplusplus.com/reference/iostream/ifstream/了解更多使用read(),get(),getLine()和许多其他强大流function的方法。

我认为最简单的方法是使用这样的fread()

 fread(buffer, nbytes, sizeof(char), in_file);