1

所有这一切可能是一个真正简单的,但我错过了一些东西,希望你能提供帮助。好的,这是我的问题,我可以说得很简单。

readfile在使用 USB 设备后返回一个缓冲区。这一切正常,我可以通过使用这样的循环来很好地输出缓冲区

for (long i=0; i<sizeof(buffer); i++)  //for all chars in string
{
    unsigned char c = buffer[i];

    switch (Format)
    {
        case 2:         //hex
            printf("%02x",c);
        break;
        case 1:         //asc
            printf("%c",c);
        break;
    }  //end of switch format
}

当我使用 text ( %c) 版本时,我可以按照我预期的方式在屏幕上看到缓冲区中的数据。但是我的问题是当我使用sscanf. 我strstr用来搜索缓冲区中的一些键并用于sscanf检索其数据。然而,sscanf失败。可能是什么问题呢?

下面是我用来扫描缓冲区的代码示例,它适用于这个独立版本。上面代码中的缓冲区部分无法读取。即使我可以看到它printf

#include <stdio.h> 
#include <string.h> 
#include <windows.h> 

int main () 
{ 
    // in my application this comes from the handle and readfile
    char buffer[255]="CODE-12345.MEP-12453.PRD-222.CODE-12355" ;    
    //
    int i; 
    int codes[256];  
    char *pos = buffer;  
    size_t current = 0;  
    //  
    while ((pos=strstr(pos, "PRD")) != NULL) {  
        if (sscanf(pos, "PRD - %d", codes+current))  
            ++current;  
        pos += 4;  
    }  

    for (i=0; i<current; i++) 
        printf("%d\n", codes[i]); 
    system("pause");
    return 0; 
} 

谢谢

4

1 回答 1

2

问题是,您ReadFile在您感兴趣的数据之前给了您不可打印的字符,特别是'\0'在开头带有 a 。由于 C 中的字符串是 NUL 终止的,所有标准函数都假定缓冲区中没有任何内容。

我不知道您正在阅读的究竟是什么,但也许您正在阅读包含标题的消息?在这种情况下,您应该先跳过标题。

盲目尝试解决问题,你可以手动跳过坏字符,假设它们都在开头。

首先,让我们确保缓冲区始终是 NUL 终止的:

char buffer[1000 + 1];    // +1 in case it read all 1000 characters
ReadFile(h,buffer,0x224,&read,NULL);
buffer[read] = '\0';

然后,我们知道有.read填充的字节数ReadFile。我们首先需要从那里回过头来找出好的数据从哪里开始。然后,我们需要再往前走,找到数据不感兴趣的第一个地方。请注意,我假设在消息的末尾没有可打印的字符。如果有,那么这将变得更加复杂。在这种情况下,最好自己编写strstr不终止于'\0',但读取到给定长度的内容。

所以而不是

char *pos = buffer;

我们的确是

// strip away the bad part in the end
for (; read > 0; --read)
    if (buffer[read - 1] >= ' ' && buffer[read - 1] <= 126)
        break;
buffer[read] = '\0';
// find where the good data start
int good_position;
for (good_position = read; good_position > 0; --good_position)
    if (buffer[good_position - 1] < ' ' || buffer[good_position - 1] > 126)
        break;
char *pos = buffer + good_position;

其余的可以保持不变。

注意:我从数组的后面开始,因为假设开头是标题,那么它可能包含可能被解释为可打印字符的数据。另一方面,最后它可能是全零或什么的。

于 2012-07-20T14:18:56.957 回答