gpt4 book ai didi

c - 如何在输出中仅打印文件中检测到的字符串的行

转载 作者:行者123 更新时间:2023-11-30 18:10:45 25 4
gpt4 key购买 nike

假设我有一个文件,其中每一行都包含信息。在这种格式中:信息名称:信息。这个文件中有很多信息。我设法使用“strstr”获取代码中信息的名称。但问题是当我 printf.它输出直到 EOF(文件结束),而不是行尾 (\n)。问题是:当我找到字符串时如何获得完整的行。如果该字符串出现多次怎么办?谢谢

char* p; // Pointer
content=charge_file("cpuinfo.txt"); // This function charge the cpu informations in a file called cpuinfo.txt
p=strstr(content,"processor"); // I'm looking for the String "processor"

while(p!=NULL){ // While not end of file
p++;
if(p=strstr(p,"processor")){
count++; // New processor found
}
printf("%d",count);// number of processors
}```

最佳答案

如果您想要做的只是比较每行的开头,然后记录比较与搜索字符串匹配的次数,那么您可以很容易地做到这一点。该方法是使用 fgets() 将每一行读入足够大小的固定缓冲区,然后使用 strncmp 将行的开头与搜索字符串进行简单比较。如果比较测试为真,则增加计数器。

例如,您可以执行类似于以下操作的操作,其中要读取的文件名由程序的第一个参数提供,而要搜索每行开头的术语作为第二个参数提供:

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

#define MAXC 2048 /* if you need a constant, #define one (or more) */

int main (int argc, char **argv) {

char buf[MAXC]; /* buffer to hold each line in file */
char *cmpstr = argc > 2 ? argv[2] : "processor"; /* compare string */
size_t cmplen = strlen (cmpstr), nstr = 0; /* length to compare, count */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : NULL; /* open file */

if (!fp) { /* validate file open for reading */
perror ("file open failed");
return 1;
}

while (fgets (buf, MAXC, fp)) /* read each line */
if (strncmp (buf, cmpstr, cmplen) == 0) /* does start match? */
nstr++; /* increment count */
fclose (fp); /* close file */

printf ("%zu - %s(s)\n", nstr, cmpstr); /* output results */

return 0;
}

(注意:不要吝惜缓冲区大小。您宁愿 100,000 个字符太多,也不愿 1 个字符太少)

示例使用/输出

直接读取/proc/cpuinfo,你会这样做:

$ ./bin/cmpleadingstr /proc/cpuinfo processor
4 - processor(s)

如果您还想输出每个匹配的字符串,只需包含对匹配字符串的 fputs 调用,例如

    while (fgets (buf, MAXC, fp))                   /* read each line */
if (strncmp (buf, cmpstr, cmplen) == 0) { /* does start match? */
fputs (buf, stdout); /* output string */
nstr++; /* increment count */
}

输出打印字符串

$ ./bin/cmpleadingstr /proc/cpuinfo processor
processor : 0
processor : 1
processor : 2
processor : 3

4 - processor(s)

(注意:添加总数之前的换行符)

仔细检查一下,如果您还有其他问题,请告诉我。如果您因任何原因无法使用 string.h 库,您可以仅使用循环来获取搜索词长度以及初始比较。

关于c - 如何在输出中仅打印文件中检测到的字符串的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56085469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com