简体   繁体   English

将recvfrom()结果接收到的缓冲区与文本文件进行比较

[英]Comparing received buffer as a result of recvfrom() to a text file

I have a Buffer received as a result of recvfrom(). 由于recvfrom(),我收到了一个缓冲区。 lets say, 可以说

char receiveBuffer[12] = "NewClient 5"; char receiveBuffer [12] =“ NewClient 5”;

I want have a text file which looks like this: 我想要一个文本文件,如下所示:

NewClient 1 192.168.1.1 8881
NewClient 2 192.168.1.1 8882
NewClient 3 192.168.1.1 8883
NewClient 4 192.168.1.1 8884
NewClient 5 192.168.1.1 8885
NewClient 6 192.168.1.1 8886
NewClient 7 192.168.1.1 8887
NewClient 8 192.168.1.1 8888
and so on..

Lets suppose receiveBuffer has "NewClient 5" in it. 假设receiveBuffer中有“ NewClient 5”。 Now what I want is that compare my receiveBuffer with contents of the file. 现在我想要的是将我的receiveBuffer与文件内容进行比较。 When receiveBuffer matches contents of the file eg in this case Line#5 has same starting contents as in my receiveBuffer, then I want to copy the corresponding number "192.168.1.1 8885" to a sendBuffer. 当receiveBuffer与文件内容匹配时,例如,在这种情况下,第5行的起始内容与我的receiveBuffer中的内容相同,那么我想将相应的数字“ 192.168.1.1 8885”复制到sendBuffer中。

How can this be done? 如何才能做到这一点? How would I compare only starting 11 bytes including a space of text file with my receiveBuffer? 如何只将包含文本文件空间的前11个字节与我的receiveBuffer比较? :( :(

I can do it by reading the file character by character by using getc() but I don't know how to compare a fixed number of bytes from file and if the comparison is false then jump to next line ignoring all other remaining bytes in that line? 我可以通过使用getc()逐个字符地读取文件来做到这一点,但我不知道如何比较文件中固定数量的字节,如果比较结果为假,则跳转到下一行,而忽略其中的所有其他剩余字节线?

Any help is welcome. 欢迎任何帮助。 Thanks in advance :) 提前致谢 :)

char * filename; // needs to be defined somewhere
FILE* fp = fopen(filename, "r");

char line[1024]; // assuming 1024 is the longest a line can be
while (fgets(line, sizeof(line), fp)) {
    if (!memcmp(line, receiveBuffer, strlen(receiveBuffer))) {
        // found the line

        char * remainder_of_line = line + strlen(receiveBuffer);
        // do whatever you want with the rest of the line found at remainder_of_line


        // optionally if you are only interested in the first matching line
        break;
    }
}

fclose(fp);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM