C语言 如何显示文本文件中与前五个字符匹配的行作为输入



我正在尝试读取文本文件并比较前五个字符,如果前五个字符匹配,则打印该行。我有这样的文本文件:

03 09 Add this text to file once 
03 09 Add this text to file once 
12 29 Add this text to file once 

到目前为止,我能够使用以下代码打印文本文件的内容:

while ((c = getc(f)) != EOF) { putchar(c); }

我的输入参数与日期03 09,如果前五个字符匹配,那么我必须打印整行。

怎么做?

您可以采取多种方法。最直接的方法之一是读取文件中的第一行,验证它至少包含 5 个字符,然后将其保存到引用缓冲区以比较后续的每一行。strncmp函数将允许您比较任意两个字符串中的第一个'x'字符数。在保存的缓冲区上调用strncmp,读取每个新行并比较前 5 个字符将告诉您每个字符串的前五个字符是否相同。

#include <stdio.h>
#include <string.h>
enum { MAXC = 64 }; /* constant for max characters per read */
int main (int argc, char **argv) {
    char s1[MAXC] = "";
    char buf[MAXC] = "";
    size_t idx = 0; /* open given file (default: stdin) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
    if (!fp) {  /* validate file open for reading */
        fprintf (stderr, "error: file open failed '%s'.n", argv[1]);
        return 1;
    }
    while (fgets (buf, MAXC, fp)) {     /* read each line  */
        if (!idx++) {                   /* if 1st store s1 */
            strcpy (s1, buf);
            printf ("%s", s1);
            if (strlen (s1) < 5) {      /* check 5 chars   */
                fprintf (stderr, "error: invalid first line.n");
                return 1;
            }
            else continue;              /* read next line  */
        }
        if (strncmp (s1, buf, 5) == 0)  /* commpare 1st 5 chars in each line */
            printf ("%s", s1);
    }
    if (fp != stdin) fclose (fp);       /* close file */
    return 0;
}

输出

$ ./bin/first5 <../dat/first5.txt
03 09 Add this text to file once
03 09 Add this text to file once

注意:您可以通过检查每行的strlen小于数组大小(-1以考虑 NUL 终止字符)以及每行中的最后一个字符是否为newline来添加每行不超过数组大小的验证。如果您的行长等于数组大小 -1 并且最后一个字符不是 newline ,则在该行中保留其他字符,在尝试检查下一行之前应读取并丢弃这些字符。那是留给你的。

查看示例,如果您有任何问题,请告诉我。

试试这个:(我正在使用上一个回复中的 fgets()。请检查是否正确)

while(fgets(line,sizeof(line),file))
{
    if((line[0]=='0')&&(line[1]=='3')&&(line[2]==' ')&&(line[3]=='0')&&(line[4]=='9')){
           print("%sn",line);
    }
}

这段代码非常基本。它不在乎您行中有多少个字符,而只是检查前 5 个字符以查看它们是否匹配。如果有任何格式问题,则它不会检测到它。

这个呢?它从名为 input.txt 的文件中获取文本,从标准输入中获取模式。我假设文件中一行的最大长度为 99。如果需要,您可以更改它。

#include <stdio.h>
#include <string.h>
int main()
{
    char inp[100],line[100], temp[6];
    FILE *file = fopen("input.txt", "r");
    fgets(inp,sizeof(inp),stdin);
    inp[5]=0;
    while(fgets(line,sizeof(line),file))
    {
        if(strlen(line)<5) continue;
        strncpy(temp, line, 5);
        temp[5] = 0;
        if(!strcmp(inp,temp)) printf("%s", line);
    }
    fclose(file);
    return 0;
}

最新更新