c++从文件中查找特定的字符串

fopen打开文件1.txt,写入内存buffer,然后_tcsstr进行数据比对,为什么总是失败?
1.txt内文件如下

KB3150513
KB3211320
KB4013418
KB4014329
KB4013429

/*源代码*/
#include "stdafx.h"
#include
#include
#pragma warning(disable:4996)
int main()
{
FILE * pFile;
long lSize;
LPTSTR buffer;
size_t result;

/* 若要一个byte不漏地读入整个文件,只能采用二进制方式打开 */
pFile = fopen("1.txt", "rb");
if (pFile == NULL)
{
    fputs("File error", stderr);
    exit(1);
}

/* 获取文件大小 */
fseek(pFile, 0, SEEK_END);
lSize = ftell(pFile);
rewind(pFile);

/* 分配内存存储整个文件 */
buffer = (LPTSTR)malloc(sizeof(LPTSTR)*lSize);
if (buffer == NULL)
{
    fputs("Memory error", stderr);
    exit(2);
}

/* 将文件拷贝到buffer中 */
result = fread(buffer, 1, lSize, pFile);
if (result != lSize)
{
    fputs("Reading error", stderr);
    exit(3);
}
/* 现在整个文件已经在buffer中,可由标准输出打印内容 */
printf("%s\n\n\n\n", buffer);

LPTSTR patch = _T("KB4013429");
if (_tcsstr(buffer, patch))
{
    printf("ok\n");
}
else
    printf("fail\n");

printf("finish\n");
/* 结束演示,关闭文件并释放内存 */
fclose(pFile);
free(buffer);
return 0;

}
图片说明

powershell -c "systeminfo | Out-File -Encoding unicode 1.txt"

 #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    FILE * pFile;
    long lSize;
    size_t result;
    /* 直接使用文本方式打开 */
    pFile = fopen("e:\\1.txt", "r");
    /* 获取文件大小 */
    fseek(pFile, 0, SEEK_END);
    lSize = ftell(pFile);
    rewind(pFile);
    char* buffer = (char*)malloc(lSize + 1);
    /* 读入所有文本 */
    fread(buffer, lSize, lSize, pFile);
    fclose(pFile);
    buffer[lSize] = '\0'; /* 写入字符串结束符 */
    if (strstr(buffer, "KB4013429") >= 0)
        printf("OK\n");
    else
        printf("fail\n");
    free(buffer);
    return 0;
}

vs2015默认工程编码是Unicode。你二进制度去接进来要编码处理。

用这个直接搞定
char *strstr(char *str1, const char *str2);
语法:
1

  • strstr(str1,str2) str1: 被查找目标 string expression to search. str2: 要查找对象 The string expression to find. 返回值:若str2是str1的子串,则返回str2在str1的首次出现的地址;如果str2不是str1的子串,则返回NULL。

powershell -c "systeminfo | Out-File -Encoding unicode 1.txt"

powershell -c "Set-Content 'm.txt' -Value (systeminfo) -Encoding Unicode"