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

标签 c windows string text-files

由于 recvfrom(),我收到了一个缓冲区。可以说,

char receiveBuffer[12] = "NewClient 5";

我想要一个如下所示的文本文件:

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..

假设 receiveBuffer 中有“NewClient 5”。 现在我想要的是将我的 receiveBuffer 与文件的内容进行比较。当 receiveBuffer 匹配文件的内容时,例如在这种情况下,第 5 行的起始内容与我的 receiveBuffer 中的相同,然后我想将相应的数字“192.168.1.1 8885”复制到 sendBuffer。

如何做到这一点?我如何将仅包含文本文件空间的起始 11 个字节与我的 receiveBuffer 进行比较? :(

我可以通过使用 getc() 逐字符读取文件来做到这一点,但我不知道如何比较文件中固定数量的字节,如果比较为假,则跳转到下一行,忽略所有其他剩余该行中的字节数?

欢迎任何帮助。提前致谢:)

最佳答案

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);

关于将 recvfrom() 的结果接收到的缓冲区与文本文件进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16960160/

相关文章:

c++ - 在 C++ 中使用 setInfo() 会导致 E_ADS_INVALID_USER_OBJECT

CS50 第 1 周,信用 - 如果比较问题?整数大小限制?

java - 使用 BouncyCaSTLe (java) 和 Gcrypt (C) 加密给出不同的结果

c++ - Windows中的互斥问题

java - (Java)程序在我想输入字符串时忽略扫描仪

c - 使用strstr时如何表示 "if substring present in string do something"?

string - 如果字符串为空,则使用 AWK 打印指定的文本

c - 向 char[5] 写入 5 个字符会影响 int

c - 视力有限的寻路

java - System.currentTimeMillis 在 winxp 上使用 Java 以外的其他语言的准确性如何?